kuangbin专题十六 KMP&&扩展KMP HDU2328 Corporate Identity

Beside other services, ACM helps companies to clearly state their “corporate identity”, which includes company logo but also other signs, like trademarks. One of such companies is Internet Building Masters (IBM), which has recently asked ACM for a help with their new identity. IBM do not want to change their existing logos and trademarks completely, because their customers are used to the old ones. Therefore, ACM will only change existing trademarks instead of creating new ones.

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.

InputThe input contains several tasks. Each task begins with a
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();
}
}

上一篇:kuangbin专题十六 KMP&&扩展KMP HDU1686 Oulipo


下一篇:【原创】Kakfa utils源代码分析(三)