Source Code
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vl;
typedef pair<ll, ll> pl;
typedef long double ld;

#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define max(a, b) (a>b ? a : b)
#define min(a, b) (a<b ? a : b)
#define FAST ios::sync_with_stdio(0), cin.tie(0),cout.tie(0)


const int N = int(1e6) + 3;
const int MOD = int(1e9) + 7;

int n,k;
string s;
int cnt[30];
int main() {
    FAST;
    //freopen("easy", "r", stdin);
    cin >> n >> k;
    cin >> s;
    for(int i=0;i<n;i++){
        cnt[s[i]-'a']++;
    }
    for(int i=0;i<26;i++){
        if (cnt[i]==0)
            continue;
        if(cnt[i]<k){
            cout << 3;
            return 0;
        }
        if(cnt[i]%k<=cnt[i]/k){
            continue;
        }else{
            cout << 3;
            return 0;
        }
    }
    vector<pair<int,int> > vv;
    for(int i=0;i<26;i++){
        if(cnt[i]==0)
            continue;
        vv.pb({cnt[i]%k,i});
    }
    sort(rall(vv));
    string a="";
    string res="";
    for(auto u:vv){
        for(int i=0;i<u.fi;i++){
            a+=char('a'+u.se);
            res+=char('a'+u.se);
        }
    }
    for(auto u:vv){
        for(int i=0;i<(cnt[u.se]/k-u.fi)%k;i++){
            a+=char('a'+u.se);
        }
    }
    if(res==a){
        cout << 3;
        return 0;
    }
    if(res.size()==0){
        cout << 1 << endl;
    }else{
        cout << 2 << endl;
    }
    for(int i=0;i<k;i++){
        cout << a;
    }
    cout << res;



    return 0;
}
Copy
Repeating Strings Mtaylor
GNU G++17
5 ms
2.5 MB
Wrong Answer