您的位置:首页 > 编程语言 > Go语言

Codeforces 676 C. Vasya and String

2016-06-09 16:54 323 查看
题目链接:http://codeforces.com/contest/676/problem/C

题目大意:一个字符串只包含a和b,可以改变其中k个,求最大的美丽值,美丽值定义为子串中所含字符均相同的的最长子串的长度

题目分析:定义起点和终点,直接贪心。对于k次操作,要么全换a要么全换b,对这两种情况取最大即可,算的时候用两点法,r向右直到k用完,然后l从左开始加,不断还原k值(由于是对于一个子串的更改,要使子串最长,那么更改的字符必定在其中即更改的顺序是连续的中间不能有没有更改的)

代码如下:#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
using namespace std;
typedef __int64 LL;

double dp[12][12];
int n, k;
string str;

int solve(char ch )
{
int l = 0, r = 0, ans = 0, cnt = 0;
while( r < n && l < n )
{

while( (str[r] == ch || cnt < k ) && r < n )// 找到右端点的位置
{
if( str[r] != ch ) cnt++;
r++;
}
ans = max( ans, r-l );
while( l<=r && str[l] == ch ) l++;//子串的左端点右移
l++;
cnt--;
}
return ans;
}

int main()
{
while( scanf("%d %d", &n, &k ) != EOF )
{
cin>>str;
printf("%d\n",max( solve( 'a' ) ,solve( 'b' ) ));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm 两点法