#pragma GCC optimize("O3") #pragma GCC target("tune=native") #pragma GCC target("avx") #include #include #include #include using ll = long long; int main() { int N, K; std::cin >> N >> K; std::vector a(N); for (int i = 0; i < N; i++) { std::cin >> a[i]; } auto comp = [](const std::string& s1, const std::string& s2) { return s1 + s2 == s2 + s1 ? s1.size() > s2.size() : s1 + s2 > s2 + s1; }; std::sort(a.begin(), a.end(), comp); std::vector ind(N); std::iota(ind.begin(), ind.end(), 0); auto next = [&]() -> bool { std::string now; for (int i = 0; i < N; i++) { now += a[ind[i]]; } std::string max; std::vector maxind; for (int i = N - 2, icnt = 0; i >= 0; i--) { if (ind[i] >= ind[i + 1]) { continue; } icnt++; for (int j = N - 1, jcnt = 0; j > i; j--) { if (ind[j] <= ind[i]) { continue; } jcnt++; std::swap(ind[i], ind[j]); std::reverse(ind.begin() + i + 1, ind.end()); for (int j = N - 1; j > i; j--) { std::swap(ind[i + 1], ind[j]); std::string s; for (int i = 0; i < N; i++) { s += a[ind[i]]; } if (s < now and max < s) { max = s, maxind = ind; } std::swap(ind[i + 1], ind[j]); } std::reverse(ind.begin() + i + 1, ind.end()); std::swap(ind[i], ind[j]); if (jcnt > 20) { break; } } if (icnt > 20) { break; } } return ind = maxind, (max != ""); }; for (int i = 0; i < K; i++) { for (int i = 0; i < N; i++) { std::cout << a[ind[i]]; } std::cout << std::endl; if (not next()) { break; } } return 0; }