Source Code
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
#define ll long long
#define X first
#define Y second
#define sz(x) (int)((x).size())
#define all(x) x.begin(), x.end()
#define pii pair<int, int>
#define pll pair<ll, ll>

using namespace std;
using namespace std;
//using namespace __gnu_cxx;
using namespace __gnu_pbds;
template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

typedef vector<int> vi;
typedef vector<pii> vii;
typedef vector<vi> adjList;
typedef pair<int, pair<int, int>> iii;
typedef vector<unsigned int> vui;
typedef vector<ll> vll;
typedef vector<double> vd;
typedef vi vm;
typedef vector<vm> Mat;



int main() {
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#else
    //    freopen("outofplace.in", "r", stdin);
    //    freopen("outofplace.out", "w", stdout);
#endif
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0), cout.precision(10), cout << fixed;

    int n, k; cin >> n >> k;
    string s; cin >> s;
    vi freq(26);
    for (int i = 0; i < n; ++i) {
        ++freq[s[i] - 'a'];
    }

    int max_mod = 0;
    bool f = false;
    for (int i = 0; i < 26; ++i) {
        max_mod = max(max_mod, freq[i] % k);
        if (freq[i] && freq[i] % k == 0) f = true;
        if (freq[i] % k > 1) {
            cout << 3 << '\n';
            return 0;
        }
        if (freq[i] % k == 1 && freq[i] == 1) {
            cout << 3 << '\n';
            return 0;
        }
    }

    if (!f) {
        cout << 3 << '\n';
        return 0;
    }

    if (max_mod == 0) {
        cout << 1 << '\n';
        string ans;
        for (int i = 0; i < 26; ++i) {
            for (int j = 0; j < freq[i] / k; ++j) {
                ans.push_back('a' + i);
            }
        }
        for (int i = 0; i < k; ++i) {
            cout << ans;
        }
        cout << '\n';
        return 0;
    }

    cout << 2 << '\n';
    string prefix;
    for (int i = 0; i < 26; ++i) {
        if (freq[i] % k == 1) {
            prefix.push_back('a' + i);
            freq[i] -= k + 1;
        }
    }

    string ans = prefix;


    for (int i = 0; i < 26; ++i) {
        for (int j = 0; j < freq[i] / k; ++j) {
            ans.push_back('a' + i);
        }
    }

    for (int i = 0; i < k; ++i) {
        cout << ans;
    }
    cout << prefix << '\n';

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