本文主要是介绍hdu 2328 Corporate Identity (KMP),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
链接: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][N];
int next[N], 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[N], s2[N];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;
}
这篇关于hdu 2328 Corporate Identity (KMP)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!