HDU-2594-Simpsons’ Hidden Talents

  • kmp
    Accepted 2594 0MS 1484K 671 B G++
    #include "cstdio"
    using namespace std;
    const int MAXN = 50005;
    char s1[MAXN], s2[MAXN];
    int next[MAXN] = {-1};
    void getNext(char* s) {
        int i = 0, j = -1;
        while (s[i]) {
            if (j == -1 || s[i] == s[j]) {
                next[++i] = ++j;
            } else {
                j = next[j];
            }
        }
    }
    int kmp(char* s1, char* s2) {
        int i = 0, j = 0;
        while (s1[i]) {
            if (j == -1 || s1[i] == s2[j]) {
                j++;
                i++; 
            } else {
                j = next[j];
            }
        }
        return j;
    }
    void print(int n) {
        if (n == 0) {
            puts("0");
            return;
        }
        s1[n] = '\0';
        printf("%s %d\n", s1, n);
    }
    int main() {
        while (gets(s1)) {
            gets(s2);
            getNext(s1);
            print(kmp(s2, s1));    
        }
        return 0;
    } 

     

posted @ 2019-02-13 12:56  Jathon-cnblogs  阅读(124)  评论(0编辑  收藏  举报