codeforces 676C - Vasya and String (尺取法)

题目链接:https://codeforces.com/problemset/problem/676/C

考虑尺取法
枚举 L,对于每个 L,尽可能向右扩展 R,当 R 不能继续向右扩展时,更新答案
更新 L,同时将 k 随 L 的更新还原
**当前的区间为 \([L+1,R]\) **

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 100010;

int n,k;
int is[maxn];
char s[maxn];

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	n = read(), k = read();
	scanf("%s",s+1);
	
	memset(is,0,sizeof(is));
	int ans = 0;
	for(int l = 0, r = 0;l<n;++l){
		while((s[r+1] == 'a' || k > 0) && r<n){
			++r;
			if(s[r] != 'a'){
				is[r] = 1;
				--k;
			}
		}
		
		ans = max(ans,r - l);
		if(r==l) ++r;
		if(s[l+1] != 'a' && is[l+1]){
			++k;
			is[l+1] = 0;
		}
		
	}
	
	memset(is,0,sizeof(is));
	for(int l = 0, r = 0;l<n;++l){
		while((s[r+1] == 'b' || k > 0) && r<n){
			++r;
			if(s[r] != 'b'){
				is[r] = 1;
				--k;
			}
		}
		
		ans = max(ans,r - l);
		if(r==l) ++r;
		if(s[l+1] != 'b' && is[l+1]){
			++k;
			is[l+1] = 0;
		}
		
	}
	
	printf("%d\n",ans);
	
	return 0;
}
posted @ 2020-10-25 17:14  Tartarus_li  阅读(83)  评论(0编辑  收藏  举报