Source Code
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <iomanip>
#include <vector>
#include <string>
#include <stack>
#include <cmath>
#include <queue>
#include <map>
#include <set>

using namespace std;
int f[30];
int main(){
    ios_base::sync_with_stdio(0); cin.tie(NULL);
    int k,n,x=-1;
    string s;
    cin>>n>>k>>s;
    bool b=0,b2=0,flag=0;
    for(int i=0;i<n;i++){
        f[(s[i]-'a')]++;
        if(i!=0&&s[i]!=s[i-1]){
            flag=1;
        }
    }
    if(!flag){
        if(s.size()<k||(f[(s[0]-'a')]%k!=0&&f[(s[0]-'a')]%k>f[(s[0]-'a')]/k)){
            return cout<<3,0;
        }
        if(f[(s[0]-'a')]%k==0){
            cout<<1<<endl;
        }
        else{
            cout<<2<<endl;
        }
        return cout<<s,0;
    }
    for(int i=0;i<30;i++){
        if(f[i]!=0){
            int a=f[i]/k;
            int g=f[i]%k;
            if(a==g){
                b2=1;
            }
            if(g!=0&&g<a){
                if(b){
                    return cout<<3,0;
                }
                x=i;
                b=1;
                b2=1;
            }
            if(g>a||f[i]<k){
                return cout<<3,0;
            }
        }
    }
    if(b2){
        cout<<2<<endl;
    }
    else{
        cout<<1<<endl;
    }
    vector<pair<int,int>>v;
    for(int i=0;i<30;i++){
        if(f[i]>0&&f[i]%k!=0&&i!=x){
            v.push_back(make_pair(f[i]/k,i));
        }
    }
    if(x!=-1){
        v.push_back({f[x]/k,x});
    }
    for(int i=0;i<30;i++){
        if(f[i]>0&&f[i]%k==0&&i!=x){
            v.push_back(make_pair(f[i]/k,i));
        }
    }
    k++;
    while(k--){
        for(int i=0;i<v.size();i++){
            for(int j=0;j<min(v[i].first,f[v[i].second]);j++){
                char h=('a'+v[i].second);
                cout<<h;
            }
            f[v[i].second]-=v[i].first;
        }
    }

    return 0;
}
Copy
Repeating Strings oora
GNU G++17
17 ms
2.7 MB
Wrong Answer