题解:P5799 [SEERC 2019] Cycle String?

· · 题解

分析

我们可以用计数数组 cnt 统计每个字符出现的次数。令出现次数最多的字符为 c,字符的种类数为 t。
如果 cnt_c \le n:
此时原字符串一定有解。只要我们不故意去构造有重复子串的字符串即可。
否则:
如果 t = 1:
显然,原字符串无解。
如果 t \le 2 且 2 \times n - cnt_c \le 2:
无论怎么构造,都会有形如 \texttt{aa...abaa...a} 的子串出现两次。
否则:
原字符串有解。
注意:先判断 cnt_c 与 n 的大小关系。

代码

#include <bits/stdc++.h>

using namespace std;

string s1;
int cnt[300];
int dif, maxcnt, maxchar;

int main(){
    cin >> s1;
    int n = s1.size();
    for(const char& x : s1){
        if(!cnt[x])
            ++dif;
        ++cnt[x];
        if(cnt[x] > maxcnt){
            maxcnt = cnt[x];
            maxchar = x;
        }
    }
    if(maxcnt <= n / 2){
        cout << "YES\n";
        for(int i = 'a'; i <= 'z'; ++i){
            while(cnt[i])
                cout << static_cast <char> (i), cnt[i]--;
        }
    }
    else if(dif == 1 || (dif == 2 && n - maxcnt <= 2)){
        cout << "NO\n";
        return 0;
    }
    else{
        cout << "YES\n";
        for(int i = 1; i <= n / 2; ++i)
            cout << static_cast <char> (maxchar);
        cnt[maxchar] -= n / 2;
        for(int i = 'a'; i <= 'z'; ++i){
            if(i == maxchar)
                continue;
            if(cnt[i]){
                cout << static_cast <char> (i);
                cnt[i]--;
                break;
            }
        }
        while(cnt[maxchar])
            cout << static_cast <char> (maxchar), cnt[maxchar]--;
        for(int i = 'a'; i <= 'z'; ++i)
            while(cnt[i])
                cout << static_cast <char> (i), cnt[i]--;
    }
    return 0;
}