The 2017 ACM-ICPC Asia Qingdao J - Suffix

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;
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值