和poj 3080惊人的相似
但是这个题因为没有要求所匹配子串的长度而且给出的数据比较大
所以用kmp卡时间比较严重
我开10000的数组超时,8000的数组就过了
代码如下:
#include <stdio.h>
#include <string.h>
#define MAXC 8000
#define MAXN 510
int len[MAXC], next[MAXN];
char chs[MAXN];
char str[MAXC][MAXN];
char tmp[MAXC][MAXN];
void get_next(char p[]) {
int len_p = strlen(p);
int i = 0, j = -1;
next[0] = -1;
while(i < len_p) {
if(j==-1 || p[i]==p[j]) {
++i, ++j;
next[i] = j;
} else j = next[j];
}
}
int kmp(char s[], char t[]) {
int lens = strlen(s);
int lent = strlen(t);
int i = 0, j = 0;
get_next(s);
while(i < lent) {
if(j==-1 || t[i]==s[j]) {
++i, ++j;
} else j = next[j];
if(j == lens)
return 1;
}
return 0;
}
int main(void) {
int m, cnt, i, j, ans, minlen, index;
while(scanf("%d", &m)!=EOF && m) {
memset(tmp, 0, sizeof(tmp));
minlen = 210;
index = 0;
for(i=0; i<m; ++i) {
scanf("%s", str[i]);
len[i] = strlen(str[i]);
if(len[i] < minlen) {
minlen = len[i];
index = i;
}
}
cnt = 0;
for(i=0; i<len[index]; ++i) {
for(j=1; i+j<=len[index]; ++j) {
strncpy(tmp[cnt], str[index]+i, j);
++cnt;
}
}
/*
printf("cnt = %d\n", cnt);
for(int i=0; i<cnt; ++i)
printf("%s\n", tmp[i]);
*/
memset(chs, 0, sizeof(chs));
for(i=cnt-1; i>=0; --i) {
ans = 0;
for(j=0; j<m; ++j) {
if(!kmp(tmp[i], str[j])) {
break;
} else ans++;
}
if(ans == m && (strlen(tmp[i])>strlen(chs) || (strlen(tmp[i])==strlen(chs) && strcmp(tmp[i], chs)<0))) {
strcpy(chs, tmp[i]);
}
}
if(strlen(chs) >= 1)
printf("%s\n", chs);
else
printf("IDENTITY LOST\n");
}
return 0;
}