思路:正解应该是nlogn的,暴力最坏n^3,一些博客的二分其实也是n^2的
具体做法就是在比较两个字符串大小时先hash然后二分找最长相同部分,再判断下一个位置大小
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 = suf1suf_1suf1 + suf2suf_2suf2 + · · · + sufnsuf_nsufn . 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 s1s_1s1 , s2s_2s2 , · · · , sns_nsn . 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.
样例输入
3 3 bbb aaa ccc 3 aba aab bab 2 abababbaabbababba abbabbabbbababbab
样例输出
baaac aaabab aab
题目来源
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ull base=131;
#define mod
#define maxn 605000
ull p[maxn];ull h[maxn];
ull get_hash(ull l,ull mid)
{
return h[l]-h[l-mid]*p[mid];
}
string str[maxn];char ans[maxn];
int len[maxn];
ull check(ull x,ull y)
{
ull l=1,r=y;
while(l<=r)
{
ull mid=(l+r)/2;
//cout<<"l="<<l<<" r="<<r<<" mid="<<mid<<'\n';
if(get_hash(x,mid)==get_hash(y,mid))
{
l=mid+1;
}
else r=mid-1;
}
if(l==y+1) return 0;
return ans[x-r]<ans[y-r];
}
int main()
{
ull T;
p[0]=1;
for(ull i=1;i<=maxn-100;i++)
{
p[i]=p[i-1]*base;
}
cin>>T;
while(T--)
{
ull n;
cin>>n;
for(ull i=1;i<=n;i++)
{
cin>>str[i];
len[i]=str[i].size();
}
ull id=0;
for(ull i=n;i>=1;i--)
{
//cout<<"i="<<i<<" id="<<id<<'\n';
ans[++id]=str[i][len[i]-1];
h[id]=h[id-1]*base+str[i][len[i]-1];
ull to=1;
ull t=id;
for(int j=(int)(len[i])-2;j>=0;j--)
{
//cout<<"i="<<i<<" j="<<j<<'\n';
ans[id+to]=str[i][j];
h[id+to]=h[id+to-1]*base+str[i][j];
if(check(id+to,t))
{
t=id+to;
}
to++;
}
id=t;
}
for(ull i=id;i>=1;i--) cout<<ans[i];
cout<<'\n';
}
}
/*
3
3
bbb
aaa
ccc
*/