HDU 1867 A + B for you again——kmp

来源:互联网 发布:linux top 某个进程 编辑:程序博客网 时间:2024/06/05 14:18

注意kmp函数中i==lens时才能返回j,否则返回0,因为a的后缀要严格等于b的前缀(kmp比较的是a的后缀和b而不是a的子串和b)


#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 1e5 + 10;char s[maxn], p[maxn], ans1[maxn], ans2[maxn];int Next[maxn];void makeNext(const char *p, int lenp) {    int pos = 0, len = 0;    Next[pos] = len;    for (pos = 1; pos < lenp; pos++) {        while (len && p[pos] != p[len]) len = Next[len - 1];        if (p[pos] == p[len]) len++;        Next[pos] = len;    }}int kmp(const char *s, const char *p, int lens, int lenp) {    makeNext(p, lenp);    int i, j;    for (i = 0, j = 0; i < lens && j < lenp; i++) {        while (j && s[i] != p[j]) j = Next[j - 1];        if (s[i] == p[j]) j++;    }    if (i == lens) return j;    return 0;}int main() {    while (~scanf("%s %s", s, p)) {        int lens = strlen(s), lenp = strlen(p);        int temp1 = kmp(s, p, lens, lenp), temp2 = kmp(p, s, lenp, lens);        strcpy(ans1, s);        strcpy(ans1 + lens, p + temp1);        strcpy(ans2, p);        strcpy(ans2 + lenp, s + temp2);        if (temp1 > temp2) {            printf("%s\n", ans1);        }        else if (temp1 < temp2) {            printf("%s\n", ans2);        }        else {            printf("%s\n", strcmp(ans1, ans2) >= 0 ? ans2 : ans1);        }    }    return 0;}