Codeforces Round #638 (Div. 2) C.Phoenix and Distribution
题目链接
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a1,a2,…,ak such that every letter of s goes to exactly one of the strings ai. The strings ai do not need to be substrings of s. Phoenix can distribute letters of s and rearrange the letters within each string ai however he wants.
For example, if s= baba and k=2, Phoenix may distribute the letters of his string in many ways, such as:
- ba and ba
- a and abb
- ab and ab
- aa and bb
But these ways are invalid:
- baa and ba
- b and ba
- baba and empty string (ai should be non-empty)
Phoenix wants to distribute the letters of his string s into k strings a1,a2,…,ak to minimize the lexicographically maximum string among them, i. e. minimize max(a1,a2,…,ak). Help him find the optimal distribution and print the minimal possible value of max(a1,a2,…,ak).
String x is lexicographically less than string y if either x is a prefix of y and x≠y, or there exists an index i (1≤i≤min(|x|,|y|)) such that xi < yi and for every j (1≤j<i) xj=yj. Here |x| denotes the length of the string x.
Input
The input consists of multiple test cases. The first line contains an integer t (1≤t≤1000) — the number of test cases. Each test case consists of two lines.
The first line of each test case consists of two integers n and k (1≤k≤n≤105) — the length of string s and the number of non-empty strings, into which Phoenix wants to distribute letters of s, respectively.
The second line of each test case contains a string s of length n consisting only of lowercase Latin letters.
It is guaranteed that the sum of n over all test cases is ≤105.
Output
Print t answers — one per test case. The i-th answer should be the minimal possible value of max(a1,a2,…,ak) in the i-th test case.
Example
input
6
4 2
baba
5 2
baacb
5 3
baacb
5 3
aaaaa
6 4
aaxxzz
7 1
phoenix
output
ab
abbc
b
aa
x
ehinopx
典型的思维题~
我们要把字符串分成
k
k
k 个部分,且使字符串的最大字典序最小,肯定首先想到排序,相当于我们把排序后的前
k
k
k 个字符作为首元素,然后逐个插入字符即可~
插入要分几种情况:
1.如果前
k
k
k 个字符不完全相同,那么只要输出第
k
k
k 个字符即可,此时把后面的字符都插入到前
k
−
1
k-1
k−1 个字符后面可以使字典序最小
2.前
k
k
k 个字符完全相同,首先输出这个字符,然后考虑第
k
+
1
k+1
k+1 个元素到第
n
n
n个元素的输出:
- 如果他们完全相同,此时只要均分就能保证最小
- 如果它们不完全相同,要保证最小,必须要把它们全部输出才行
AC代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
main()
{
int t,n,k;
cin>>t;
while(t--){
string s;
cin>>n>>k>>s;
sort(s.begin(),s.end());
if(s[0]!=s[k-1]){
putchar(s[k-1]);
}
else{
cout<<s[0];
if(s[k]!=s[n-1]){
for(int i=k;i<n;i++) putchar(s[i]);
}
else{
for(int i=0;i<(n-1)/k;i++) putchar(s[k]);
}
}
puts("");
}
return 0;
}