您的位置:首页 > 其它

hdu 2328 Corporate Identity (KMP)

2014-03-19 22:56 423 查看
链接:http://acm.hdu.edu.cn/showproblem.php?pid=2328

求公共字串,暴力+KMP

代码:

#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
const int N = 205;

char s[4005]
;
int next
, n, t;

void get_next(char *seq, int m) {
next[0] = -1;
int j = next[0];
for (int i = 1; i < m; i++) {
while (j >= 0 && seq[i] != seq[j + 1]) j = next[j];
if (seq[i] == seq[j + 1]) j++;
next[i] = j;
}
}

bool kmp(char *seq, char *seq1, int n, int m) {
int j = next[0], ans = 0;
for (int i = 0; i < n; i++) {
while (j >= 0 && seq[i] != seq1[j + 1]) j = next[j];
if (seq[i] == seq1[j + 1]) j++;
if (j == m - 1) {
return true;
}
}
return false;
}

bool judge(char *seq1) {
for (int i = 1; i < n; i++)
if (!kmp(s[i], seq1, strlen(s[i]), strlen(seq1)))
return false;
return true;
}

void solve() {
char ans
, s2
;
strcpy(ans, "IDENTITY LOST");
int len = strlen(s[0]);
for (int i = 0; i < len; i++) {
get_next(s[0] + i, len - i);
memset(s2, 0, sizeof(s2)); int s2n = 0;
for (int j = i; j < len; j++) {
s2[s2n++] = s[0][j];
if (judge(s2)) {
if (strcmp(ans, "IDENTITY LOST") == 0)
strcpy(ans, s2);
else if (strlen(ans) < strlen(s2))
strcpy(ans, s2);
else if (strlen(ans) == strlen(s2) && strcmp(ans, s2) > 0)
strcpy(ans, s2);
}
}
}
printf("%s\n", ans);
}

int main() {
while (~scanf("%d", &n) && n) {
for (int i = 0; i < n; i++)
scanf("%s", s[i]);
solve();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: