B. Reverse Binary Strings

题意:给定一个偶数长度的01串,0跟1的个数相等。

   给定操作:任意选择连续区间进行翻转

   要求:最后的串为010101....或者10101010.....

思路:找出所有连续1的区间,对于每一个区间,我们都减一,然后纳入总和

   找出所有连续0的区间,对于每一个区间,我们都减一,然后纳入总和

   ans=max(第一个操作,第二个操作)

至于证明,我不会。hh

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1e5+10;
 4 char a[maxn];
 5 int main()
 6 {
 7     int T;
 8     scanf("%d",&T);
 9     while(T--){
10         int n;
11         scanf("%d",&n);
12         scanf("%s",a+1);
13         int now1=0;
14         int tmp1=0;
15         for(int i=1;i<=n;i++){
16             if(a[i]=='0'){
17                 tmp1++;
18             }
19             else{
20                 if(tmp1==0) continue;
21                 now1+=tmp1-1;
22                 tmp1=0;
23             }
24         }
25         if(tmp1>0) now1+=tmp1-1;
26      //   printf("%d\n",now1);
27 
28 
29         int now2=0;
30         int tmp2=0;
31         for(int i=1;i<=n;i++){
32             if(a[i]=='1'){
33                 tmp2++;
34             }
35             else{
36                 if(tmp2==0) continue;
37                 now2+=tmp2-1;
38                 tmp2=0;
39             }
40         }
41         if(tmp2>0) now2+=tmp2-1;
42         int ans=max(now1,now2);
43        // printf("now1:%d now2:%d\n",now1,now2);
44         printf("%d\n",ans);
45     }
46     return 0;
47 }

 

posted @ 2020-11-11 21:25  古比  阅读(156)  评论(0编辑  收藏  举报