asdf sdfg asdf ghjk
asdfg asdfghjk
#include <cstdio> #include <cstring> int const MAX = 1e5 + 5; int next[MAX]; char s1[MAX], s2[MAX]; void get_next(char *a) { int i = 0, j = -1; next[0] = -1; while(a[i] != '\0') { if(j == -1 || a[i] == a[j]) { i++; j++; if(a[i] == a[j]) next[i] = next[j]; else next[i] = j; } else j = next[j]; } } int KMP(char *a, char *b) { get_next(b); int i = 0, j = 0; while(a[i] != '\0') { if(j == -1 || a[i] == b[j]) { i++; j++; } else j = next[j]; } return j; } int main() { while(scanf("%s %s", s1, s2) != EOF) { int l1 = KMP(s1, s2); int l2 = KMP(s2, s1); if(l1 == l2) { if(strcmp(s1, s2) < 0) printf("%s%s\n", s1, s2 + l1); else printf("%s%s\n", s2, s1 + l1); } else if(l1 < l2) printf("%s%s\n", s2, s1 + l2); else printf("%s%s\n", s1, s2 + l1); } }
HDU 1867 A + B for you again (KMP应用)
原文地址:http://blog.csdn.net/tc_to_top/article/details/43730301