Consider n given non-empty strings denoted by s1 , s2 , · · · , sn . Now for each of them, you need to select a corresponding suffix, denoted by suf1, suf2, · · · , sufn. For each string si, the suffix sufi is a non-empty substring whose right endpoint is the endpoint of the entire string. For instance, all suffixes of the string “jiangsu” are “u”, “su”, “gsu”, “ngsu”, “angsu”, “iangsu” and itself.
All selected suffixes could assemble into a long string T =
s
u
f
1
+
s
u
f
2
- · · · +
s
u
f
n
. Here plus signs indicate additions of strings placing the latter at the tail of the former. Your selections of suffixes would determine the lexicographical order of T . Now, your mission is to find the one with minimum lexicographical order.
Here is a hint about lexicographical order. To compare strings of different lengths, the shorter string is usually padded at the end with enough “blanks” which is a special symbol that is treated as smaller than every letters.
Input
The first line of input contains an integer T which is the total number of test cases. For each case, the first line contains an positive integer n. Each of the following n lines contains a string entirely in lowercase, corresponding to
s
1
,
s
2
, · · · ,
s
n
. The summation of lengths of all strings in input is smaller or equal to 500000.
Output
For each test case, output the string T with minimum lexicographical order.
Sample Input
3
3
bbb
aaa
ccc
3
aba
aab
bab
2
abababbaabbababba
abbabbabbbababbab
Sample Output
baaac
aaabab
aab
分析:
将n个字符串的后缀按输入顺序组合成一个字符串,求最小字典序的字符串。
可以从最后一个字符串往前找后缀,找到使当前字符串字典序最小的后缀,即为答案中要找的后缀
#include<bits/stdc++.h>
#include<string>
#define ll long long
using namespace std;
typedef unsigned long long ull;
const int N = 5e5+10;
string st[N],tmp;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
cin>>st[i];
}
string ans;
for(int i=n;i>=1;i--)
{
int l=st[i].length();
string mi=st[i].substr(l-1)+ans;
for(int j=0;j<=l-2;j++)
{
tmp=st[i].substr(j)+ans;
if(tmp<mi) mi=tmp;
}
ans=mi;
}
cout<<ans<<endl;
}
return 0;
}