题解:P16853 [GKS 2021 #E] Shuffled Anagrams
给定多组小写字母串,构造原串错排异序词:
- 字母出现频次与原串完全一致;
-
任意位置新字符
\ne 原字符; 无解输出IMPOSSIBLE,按指定格式输出每组答案。
串长
原理:字符占比过半,无论如何排列,一定存在原位重合。
- 保存字符串所有下标,按下标对应字符排序;
- 排序下标数组整体偏移
L/2 位映射填充答案,天然错位; - 偏移构造保证不存在原位相等字符。
#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
string t;
bool f(int x,int y){
return t[x]<t[y];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int m;
cin>>m;
for(int a=1;a<=m;a++){
int c[26]={0};
vector<int>v;
cin>>t;
int l=t.size();
cout<<"Case #"<<a<<": ";
for(int b=0;b<l;b++){
c[t[b]-'a']++;
v.push_back(b);
}
bool k=0;
for(int d=0;d<26;d++){
if(c[d]>l-c[d]){
k=1;
break;
}
}
if(k){
cout<<"IMPOSSIBLE\n";
continue;
}
sort(v.begin(),v.end(),f);
string r=t;
int o=l/2;
for(int b=0;b<l;b++){
int p=v[(b+o)%l];
r[v[b]]=t[p];
}
cout<<r<<endl;
}
return 0;
}