CF1626A Equidistant Letters 题解
题目大意
给定由小写字母组成的字符串 \(s\),保证其中每个字符出现不超过两次,要求重排字符串,使得任意两个同样的字符相隔的距离相同。
Solution
考虑维护出所有字符出现的次数,然后将出现两次的排两遍,出现一次的排在最后即可。可以证明这样操作出的字符串符合题意。
Code
#include<bits/stdc++.h>
#define HohleFeuerwerke using namespace std
#pragma GCC optimize(3,"Ofast","-funroll-loops","-fdelete-null-pointer-checks")
#pragma GCC target("ssse3","sse3","sse2","sse","avx2","avx")
#define int long long
HohleFeuerwerke;
inline int read(){
int s=0,f=1;char c=getchar();
for(;!isdigit(c);c=getchar()) if(c=='-') f=-1;
for(;isdigit(c);c=getchar()) s=s*10+c-'0';
return s*f;
}
inline void write(int x){
if(x<0) putchar('-'),x=-x;
if(x>=10) write(x/10);
putchar('0'+x%10);
}
const int MAXN=1e2+5;
int T; map<char,int>m;
char str[MAXN],ans[MAXN];
vector<char> memr1,memr2;
map<char,int>::iterator iter;
inline void solve(){
memset(str,0,sizeof(str));
memset(ans,0,sizeof(ans));
m.clear();scanf("%s",str+1);int n=strlen(str+1);
for(int i=1;i<=n;i++) m[str[i]]++;
memr1.clear();memr2.clear();
for(iter=m.begin();iter!=m.end();iter++)
if(iter->second==2) memr1.push_back(iter->first);
else memr2.push_back(iter->first);
int t1=memr1.size(),t2=memr2.size();
int cur=0;
for(int i=0;i<t1;i++) ans[cur++]=memr1[i];
for(int i=0;i<t1;i++) ans[cur++]=memr1[i];
for(int i=0;i<t2;i++) ans[cur++]=memr2[i];
printf("%s\n",ans);return;
}
signed main()
{
T=read();
while(T--) solve();
return 0;
}