首页 > 代码库 > UVaLive 7637 Balanced String (构造)
UVaLive 7637 Balanced String (构造)
题意:给定一个括号的序列,原先的序列是碰到左括号加1,碰到右括号减1,然后把序列打乱,让你找出字典序最小的一个答案。
析:直接从第一个括号判断就好了,优先判断左括号,如果不行就加右括号。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1e5 + 10; const int mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int a[maxn]; map<int, int> mp; int main(){ int T; cin >> T; for(int kase = 1; kase <= T; ++kase){ scanf("%d", &n); mp.clear(); for(int i = 0; i < n; ++i) scanf("%d", a+i), ++mp[a[i]]; printf("Case %d: ", kase); if((n&1) || !mp.count(1)){ printf("invalid\n"); continue; } bool ok = true; --mp[1]; int pos = 1; for(int i = 1; i < n && ok; ++i){ if(mp.count(pos+1) && mp[pos+1]) ++pos, --mp[pos]; else if(mp.count(pos-1) && mp[pos-1]) --pos, --mp[pos]; else ok = false; } if(!ok && pos){ printf("invalid\n"); continue; } for(int i = 0; i < n; ++i) ++mp[a[i]]; printf("("); pos = 1; for(int i = 1; i < n; ++i){ if(mp.count(pos+1) && mp[pos+1]) ++pos, --mp[pos], printf("("); else if(mp.count(pos-1) && mp[pos-1]) --pos, --mp[pos], printf(")"); } printf("\n"); } return 0; }
UVaLive 7637 Balanced String (构造)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。