After several other proposals, it was decided to take all existing
trademarks and find the longest common sequence of letters that is
contained in all of them. This sequence will be graphically emphasized
to form a new logo. Then, the old trademarks may still be used while
showing the new identity.
Your task is to find such a sequence.
line containing a positive integer N, the number of trademarks (2 ≤ N ≤
4000). The number is followed by N lines, each containing one trademark.
Trademarks will be composed only from lowercase letters, the length of
each trademark will be at least 1 and at most 200 characters.
After the last trademark, the next task begins. The last task is followed by a line containing zero.OutputFor each task, output a single line containing the longest
string contained as a substring in all trademarks. If there are several
strings of the same length, print the one that is lexicographically
smallest. If there is no such non-empty string, output the words
“IDENTITY LOST” instead.Sample Input
3
aabbaabb
abbababb
bbbbbabb
2
xyz
abc
0
Sample Output
abb
IDENTITY LOST 跟前面几道题都是类似的。枚举第一个串的所有后缀,然后和其余字符串匹配。得到的公共最小取最大。不断更新答案。
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int n,Next[];
vector<string> t;
string s,ans; void prekmp(string s) {
int len=s.size();
int i,j;
j=Next[]=-;
i=;
while(i<len) {
while(j!=-&&s[i]!=s[j]) j=Next[j];
Next[++i]=++j;
}
} int kmp(string t,string p) {
int len=t.size();
int i,j,res=-;
i=j=;
while(i<len) {
while(j!=-&&t[i]!=p[j]) j=Next[j];
++i;++j;
res=max(res,j);
}
return res;
} int main() {
//freopen("in","r",stdin);
while(~scanf("%d",&n)&&n) {
for(int i=;i<n;i++) {
cin>>s;
t.push_back(s);
}
string str=t[],tempstr;
int maxx=-,res;
int len=str.size();
for(int i=;i<len;i++) {
tempstr=str.substr(i,len-i);
prekmp(tempstr);
res=;
for(int j=;j<t.size();j++) {
res=min(kmp(t[j],tempstr),res);
}
if(res>=maxx&&res) {
if(res==maxx) {
string tempstr1=tempstr.substr(,maxx);
if(tempstr1<ans)
ans=tempstr1;
} else {
maxx=res;
ans=tempstr.substr(,maxx);
}
}
}
if(ans.size()) cout<<ans<<endl;
else cout<<"IDENTITY LOST"<<endl;
ans.clear();
t.clear();
}
}