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;
}
题目大意:一个字符串只包含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;
}
相关文章推荐
- Javascript SHA-1:Secure Hash Algorithm
- 浏览器运行java插件报错:Algorithm constraints check failed: MD5withRSA
- [转]可视化的数据结构和算法
- 统计文件中不小于某一长度的单词的个数(泛型算法实现)
- 使用他人的MD5编码类,修改形成密码串
- Extracting Structured Data from Web Pages
- (译)Cocos2d_for_iPhone_1_Game_Development_Cookbook:1.13使用CCTexture2DMutable调换调色盘
- Java中3DES加密
- Refactoring Notes-Refactoring Methods(3)
- 图书馆管理程序~~不过貌似功能!!有空再修修
- trainging contest#2(2011成都现场赛)I BY Hyoga
- C/C++头文件包含内容概览
- 堆栈的应用(1) 平衡符号 C++实现
- 程序员编程艺术第一章、左旋转字符串
- 程序员编程艺术:第三章续、Top K算法问题的实现
- 程序员编程艺术:第四章、现场编写类似strstr/strcpy/strpbrk的函数
- 十四、第三章再续:快速选择SELECT算法的深入分析与实现
- 程序员编程艺术:第七章、求连续子数组的最大和
- 程序员编程艺术:第八章、从头至尾漫谈虚函数
- 程序员编程艺术:第九章、闲话链表追赶问题