cf #334 C. Alternative Thinking (思维题)

题目: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值