牛客练习赛80 A-加密
加密
https://ac.nowcoder.com/acm/contest/11170/A
需要发现,反转一个0/1只会改变最多1个全1串的数量(答案),而且很好判断。
判断方法:
如果在两端,只有10...和...01这两种情况会减少答案。
如果在中间,那么当且仅当该位置和左右两边均不一样就减少答案。
所以先跑一遍得到原串的答案,然后枚举每个位置,判断这个位置反转后会不会令答案减少1即可。
#include<bits/stdc++.h>
using namespace std;
char ch[1000010];
int ans;
int main()
{
int temp=0,n=0;
for(int i=0;(ch[i]=getchar())=='0'||ch[i]=='1';++i)
{
if(!temp && ch[i]=='1') {++ans;temp=1;}
if(ch[i]=='0') temp=0;
++n;
}
if(ch[0]=='1' && ch[1]=='0') {cout<<ans-1;return 0;}
if(ch[n-1]=='1')
{
if(n-2>=0 && ch[n-2]=='0')
{cout<<ans-1;return 0;}
}
for(int i=1;i+1<n;++i)
{
if(ch[i]!=ch[i-1] && ch[i]!=ch[i+1])
{cout<<ans-1;return 0;}
}
cout<<ans;
return 0;
}