跳到正文

题解

题解:P16853 [GKS 2021 #E] Shuffled Anagrams

JohnWong约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年7月13日
收录
2026年7月15日
更新
2026年11月14日
篇幅
约 2 分钟
获赞
3
题目
P16853

版本

  1. v1当前

给定多组小写字母串,构造原串错排异序词:

  1. 字母出现频次与原串完全一致;
  2. 任意位置新字符 ≠\ne 原字符; 无解输出 IMPOSSIBLE,按指定格式输出每组答案。

串长 LL,某字符出现次数 cc,若 c>L−cc > L-c 则必然无解。

原理:字符占比过半,无论如何排列,一定存在原位重合。


  1. 保存字符串所有下标,按下标对应字符排序;
  2. 排序下标数组整体偏移 L/2L/2 位映射填充答案,天然错位;
  3. 偏移构造保证不存在原位相等字符。
C++
#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;
}
原文
存档评论1 条抓取于