二分做法,check中用了队列(因为题目标签写了队列)
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
int n,k,ans=2e9;
string s;
queue<char> q;
bool check(int x){
int res=0,cnt=0;//res表示 不优美度为x时需要开关灯的次数
int len=s.size();
q.push(s[0]);
for(int i=1;i<len;i++){
if(s[i]==q.back()){
cnt++;
q.push(s[i]);
}//若现在的字符与队尾相同,则属于连续的开着或关着的灯,放入队末
else{
while(!q.empty()){
q.pop();
}
cnt=1;
q.push(s[i]);
}//若现在的字符与队尾不同,与上述情况相反,前面相同个数未满x的出队
if(cnt>x){
res++;
cnt=1;
char c;
if(q.front()=='N') c='F';
else c='N';
while(!q.empty()){
q.pop();
}
q.push(c);
}//当同一字符个数超过x(不优美度超过x),需将最后一个字符更改,前面刚好x个的字符出队,将更改后的字符入队
}
if(res>k) return 0;
return 1;
}
int main(){
cin>>n>>k;
cin>>s;
int l=0,r=n,mid;
while(l<=r){
mid=(l+r)/2;
if(check(mid)){
ans=min(ans,mid);
r=mid-1;
}
else{
l=mid+1;
}
while(!q.empty()){
q.pop();
}
}
cout<<ans;
}