Corporate Identity
http://poj.org/problem?id=3450
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 9929 Accepted: 3275
Description
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.
Input
The 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.
Output
For 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
Source
CTU Open 2007
题意:找出n个字符串中最长的公共子串;
思路:运用Kmp的解决。枚举一个串的所有后缀,找到该后缀的与其他的所有串的最长匹配。取所有中的最大的。
代码如下:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <set>
#include <cmath>
#include <map>
#include <queue>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn = 4010;
const int maxn2= 10005;
const int inf =0x3f3f3f3f;
char w[maxn][maxn],tm[maxn];
int ne[maxn];
int n,t,ma,l;
void get_ne(){
int i,j;
j=ne[0]=-1;i=0;
while(i<l){
if(-1!=j&&tm[i]!=tm[j]) j=ne[j];
else ne[++i]=++j;
}
}
int kmp(){
int i=0,j=0,k=0,m=0;ma=100;
get_ne();
for(k=1;k<n;k++){
i=0;j=0;m=0;
while(i<t&&j<l){
while(-1!=j&&w[k][i]!=tm[j]) j=ne[j];
i++;j++;
if(j>m) m=j;
}
if(m<ma) ma=m;
}
}
int main() {
while(~scanf("%d",&n),n){
for(int i=0;i<n;i++) scanf("%s",w[i]);
int ans=0;char re[maxn];t=strlen(w[0]);
for(int i=0;i<=t;i++){
strcpy(tm,w[0]+i);l=t-i;kmp();
if(ans<ma){
ans=ma;strncpy(re,w[0]+i,ans);
re[ans]='\0';
}else if(ans==ma){
char s[maxn];
strncpy(s,w[0]+i,ans);
s[ans]='\0';
if(strcmp(s,re)<0){
strcpy(re,s);
}
}
}
if(ans==0) {
printf("IDENTITY LOST\n");continue;
}else{
printf("%s\n",re);
}
}
return 0;
}