#include <bits/stdc++.h> using namespace std; int n,t,wynik; string s; struct segment{int l; int w;}; struct compare { bool operator()(segment const&A, segment const&B) { if(A.l==B.l)return A.w>B.w; return A.l<B.l; } }; priority_queue<segment, vector<segment>, compare> Q; void modify(int k) { stack<segment> stos; while(Q.size()!=0) { segment y=Q.top(); Q.pop(); y.l=y.l-2*k; if(y.l>0)stos.push(y); } while(stos.size()!=0) { segment y=stos.top(); stos.pop(); Q.push(y); } } int main() { ios_base::sync_with_stdio(0); cin>>t; for(int e=1;e<=t;e++) { cin>>n; bool tab[n+10]; cin>>s; tab[0]=1; for(int i=1;i<=n;i++) { if(s[i-1]=='0')tab[i]=0; else tab[i]=1; } int pocz=0,kon=0; for(int i=1;i<=n;i++) { if(tab[i]==0) { if(tab[i-1]==1)pocz=i; kon=i; } else { if(pocz!=0&&kon!=0) { int k=2; if(pocz==1)k--; if(kon==n)k--; segment x; x.l=kon-pocz+1; x.w=k; if(k==1)x.l=x.l*2; Q.push(x); pocz=0; kon=0; // cout<<x.l<<" "<<x.w<<endl; } } } if(tab[n]==0) { int k=2; if(pocz==1)k--; if(kon==n)k--; segment x; x.l=kon-pocz+1; if(k==1)x.l=x.l*2; x.w=k; Q.push(x); // cout<<x.l<<" "<<x.w<<endl; pocz=0; kon=0; } wynik=0; while(Q.size()!=0) { segment x=Q.top(); Q.pop(); if(x.w==1) { x.l=x.l/2; } wynik+=x.l; if(x.w==2&&x.l!=1)wynik--; modify(x.w); } cout<<n-wynik<<endl; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | #include <bits/stdc++.h> using namespace std; int n,t,wynik; string s; struct segment{int l; int w;}; struct compare { bool operator()(segment const&A, segment const&B) { if(A.l==B.l)return A.w>B.w; return A.l<B.l; } }; priority_queue<segment, vector<segment>, compare> Q; void modify(int k) { stack<segment> stos; while(Q.size()!=0) { segment y=Q.top(); Q.pop(); y.l=y.l-2*k; if(y.l>0)stos.push(y); } while(stos.size()!=0) { segment y=stos.top(); stos.pop(); Q.push(y); } } int main() { ios_base::sync_with_stdio(0); cin>>t; for(int e=1;e<=t;e++) { cin>>n; bool tab[n+10]; cin>>s; tab[0]=1; for(int i=1;i<=n;i++) { if(s[i-1]=='0')tab[i]=0; else tab[i]=1; } int pocz=0,kon=0; for(int i=1;i<=n;i++) { if(tab[i]==0) { if(tab[i-1]==1)pocz=i; kon=i; } else { if(pocz!=0&&kon!=0) { int k=2; if(pocz==1)k--; if(kon==n)k--; segment x; x.l=kon-pocz+1; x.w=k; if(k==1)x.l=x.l*2; Q.push(x); pocz=0; kon=0; // cout<<x.l<<" "<<x.w<<endl; } } } if(tab[n]==0) { int k=2; if(pocz==1)k--; if(kon==n)k--; segment x; x.l=kon-pocz+1; if(k==1)x.l=x.l*2; x.w=k; Q.push(x); // cout<<x.l<<" "<<x.w<<endl; pocz=0; kon=0; } wynik=0; while(Q.size()!=0) { segment x=Q.top(); Q.pop(); if(x.w==1) { x.l=x.l/2; } wynik+=x.l; if(x.w==2&&x.l!=1)wynik--; modify(x.w); } cout<<n-wynik<<endl; } } |