CodeForces - 1504C Balance the Bits(思维+构造)
題目鏈接:https://vjudge.net/problem/CodeForces-1504C
題目大意:給出一個長度為 nnn 的 010101 串,現(xiàn)在要求構(gòu)造出兩個長度為 nnn 的合法括號序列,使得在 010101 串對應(yīng)為 000 的位置,兩個序列的括號不相同,反之亦然
題目分析:本以為是貪心,但后來發(fā)現(xiàn)其實是一個很簡單的構(gòu)造
首先考慮非法的情況,無論如何起止位置一定是需要匹配的,也就是說 010101 串的開頭和結(jié)尾一定都是 111 才行
其次就是必須為串的長度必須是偶數(shù)才行,否則一定無法完全匹配
然后就是 010101 串中 000 和 111 的個數(shù)都必須是偶數(shù)才行,因為假如有奇數(shù)個 000 的話,就會導致兩個串中左括號和右括號的個數(shù)不相等,而其余位置兩個序列的括號都是相等的,綜上兩個串肯定不可能同時為合法的括號序列
最后就是構(gòu)造了,設(shè) 111 的個數(shù)為 kkk,我們可以貪心去讓前 k2\frac{k}{2}2k? 個 111 放置左括號,后 k2\frac{k}{2}2k? 個 111 放置右括號
然后對于 000 的位置,我們左右括號交替放置即可,可以證明這樣一定是可行的
代碼:
// Problem: C. Balance the Bits // Contest: Codeforces - Codeforces Round #712 (Div. 2) // URL: https://codeforces.com/contest/1504/problem/C // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) x&-x using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e6+100; char s[N]; int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--) {int n;read(n);scanf("%s",s+1);int c=0;for(int i=1;i<=n;i++) {c+=s[i]=='1';}if((n&1)||c%2!=0||s[1]!='1'||s[n]!='1') {puts("NO");continue;}string ans1,ans2;int k=1;bool flag=true;for(int i=1;i<=n;i++) {if(s[i]=='1') {if(k<=c/2) {ans1+="(";ans2+="(";} else {ans1+=")";ans2+=")";}k++;} else {if(flag) {ans1+="(";ans2+=")";} else {ans1+=")";ans2+="(";}flag^=1;}}puts("YES");cout<<ans1<<endl<<ans2<<endl;}return 0; }總結(jié)
以上是生活随笔為你收集整理的CodeForces - 1504C Balance the Bits(思维+构造)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1512G S
- 下一篇: CodeForces - 1498D B