题目:http://codeforces.com/contest/604/problem/C
题意:给定长为n的01串,将一段连续的区间的值取反,求最长的01交替的串的长度(不一定要连续)。
分析:将一段连续的区间的值取反后,区间内最长交替串的长度不变,影响的只有两边的连接。所以,长度最多只能增加2。把所有可能增加交替长度的情况考虑一下就好了。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const LL INF = 1E9+9;
const int maxn = 1e5+7;
char str[maxn];
bool Find3()
{
int Max=-1,c=1;
for(int i=1;str[i];i++)
{
if(str[i]!=str[i-1])
{
c=1;
}
else
{
c++;
if(c>=3)
return true;
}
}
int cnt=0;
for(int i=1;str[i];i++)
if(str[i]==str[i-1])
cnt++;
if(cnt>=2)
return true;
return false;
}
int Find2()
{
for(int i=1;str[i];i++)
if(str[i-1]==str[i])
return 1;
return 0;
}
int main()
{
int n,i,j;
scanf("%d%s",&n,str+1);
if(n<=3)
{
printf("%d\n",n);
return 0;
}
str[0]='-';
int cnt=0;
for(i=1;str[i];i++)
{
if(str[i]!=str[i-1])
cnt++;
}
if(Find3())
{
cnt+=2;
printf("%d\n",cnt);
return 0;
}
cnt+=Find2();
printf("%d\n",cnt);
return 0;
}
将上面的代码简化一下就是:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const LL INF = 1E9+9;
const int maxn =1e6+8;
int n;
char s[maxn];
int main()
{
scanf("%d%s",&n,s);
int ret = 1,c(0);
for(int i = 1; i < n; i++)
if(s[i] == s[i - 1])
c ++;
else
ret ++;
ret += min(2, c);
printf("%d\n", ret);
return 0;
}