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

using namespace std;

#define PI 3.14159265358979323846
#define mod 1000000007
#define ll long long
#define vi vector<int>
#define ii pair<int, int>
#define pb push_back
#define all(c) (c).begin(), (c).end()

const int N = 1e6;

int n, k, freq[26], rfreq[26], tfreq[26];
string s, t, r;
bool t1 = true, t2 = true;

void findT() {
	for (int i = 0; i < 26; ++i) {
		for (int j = 0; j < freq[i] / k; ++j)
			t += ('a' + i);
	}

	for (int i = 0; i < t.size(); ++i)
		++tfreq[t[i] - 'a'];
}

int main() {
// 	freopen("input.txt", "r", stdin);
// 	freopen("output.txt", "w", stdout);

	cin >> n >> k >> s;

	for (int i = 0; i < n; ++i)
		++freq[s[i] - 'a'];

	for (int i = 0; i < 26; ++i) {
		if (freq[i] % k != 0) {
			t1 = false;
			rfreq[i] = freq[i] % k;
		}
	}

	for (int i = 0; i < 26; ++i)
		freq[i] -= rfreq[i];

	findT();

	if (t1) {
		puts("1");
		for (int i = 0; i < k; ++i)
			cout << t;
		puts("");

		return 0;
	}

	for (int i = 0; i < 26; ++i) {
		if (rfreq[i] > tfreq[i])
			t2 = false;
	}

	if (t2) {
		puts("2");
		for (int i = 0; i < 26; ++i)
			tfreq[i] -= rfreq[i];

		for (int i = 0; i < 26; ++i)
			for (int j = 0; j < rfreq[i]; ++j)
				r += ('a' + i);

		t = r;
		for (int i = 0; i < 26; ++i)
			for (int j = 0; j < tfreq[i]; ++j)
				t += ('a' + i);

		for (int i = 0; i < k; ++i)
			cout << t;
		cout << r << endl;

		return 0;
	}

	puts("3");
}
Copy
Repeating Strings omarthejuiceboi
GNU G++17
29 ms
3.1 MB
Accepted