Source Code
#include <bits/stdc++.h>
using namespace std;
    
int main (){

  #ifndef ONLINE_JUDGE
    freopen("SuhaibSawalha1","r",stdin);
  #endif

  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  int n, k;
  string s;
  cin >> n >> k >> s;
  int f[26] = {};
  for (char c : s) {
    ++f[c - 'a'];
  }
  bool ok = 1;
  string w;
  int r[26] = {};
  for (int i = 0; i < 26; ++i) {
    ok &= f[i] % k == 0; 
    w += string(f[i] / k, char(i + 'a'));
    r[i] += f[i] / k;
  }
  if (ok) {
    cout << "1\n";
    while (k--) {
      cout << w;
    }
    return 0;
  }
  ok = 1;
  string t;
  int l[26] = {};
  for (int i = 0; i < 26; ++i) {
    int x = f[i] - r[i] * k;
    ok &= x <= r[i];
    t += string(x, char(i + 'a'));
    l[i] += x;
  }
  if (ok) {
    w = t;
    for (int i = 0; i < 26; ++i) {
      w += string(r[i] - l[i], char(i + 'a'));
    }
    cout << "2\n";
    while (k--) {
      cout << w;
    }
    cout << t;
    return 0;
  }
  cout << "3\n";

  return 0;
}
Copy
Repeating Strings SuhaibSawalha1
GNU G++17
4 ms
3.7 MB
Accepted