字符最大间隔排列
B-完美串_牛客挑战赛79
思路:
代码:
string s;
cin>>s;
array<int,26> cnt={0};
for(auto c: s){
++cnt[c-'a'];
}
int n=s.size();
auto check=[&](int x){
auto c=cnt;
array<int,26> lst;
lst.fill(-x);
for(int i=0; i<n; i++){
int id=-1;
for(int j=0; j<26; j++){
if(c[j] && i-lst[j]>=x &&( id==-1 || c[j]>c[id])){
id=j;
}
}
if(id==-1){
return false;
}
--c[id], lst[id]=i;
}
return true;
};
for(int x= min(n,26); x>=1; x--){
if(check(x)){
cout<<x<<'\n';
array<int,26> lst;
lst.fill(-x);
for(int i=0; i<n; i++){
int id=-1;
for(int j=0; j<26; j++){
if(cnt[j] && i-lst[j]>=x && (id==-1 || cnt[j]>cnt[id])){
id=j;
}
}
--cnt[id], lst[id]=i;
cout<<char(id+'a');
}
cout<<'\n';
break;
}
}