HDU 2594 KMP的next数组

传送门:题目

题解:

纯KMP,考的就是KMP中next数组的具体含义。
如果不理解next,可以参考这篇博客:KMP中next数组含义

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#define debug(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=100010;//第一开始maxn只开了5万,一直tle,我还以为要用scanf才能过
int KMP_next[maxn];
void kmp_pre(string x, int m, int KMP_next[]) {//kmp未优化版
    //如果多次使用KMP,不需要对next  memset
    //abab  -> next={-1,0,0,1,2};
    int i = 0, j = KMP_next[0] = -1;
    while (i < m) {
        while (j != -1 && x[i] != x[j])
            j = KMP_next[j];
        KMP_next[++i] = ++j;
    }
}
int main(void){
    ios::sync_with_stdio(false);
    string a,b;
    while(cin>>a>>b){
        a=a+"&"+b;
        int len_a_post=a.size();
        kmp_pre(a,len_a_post,KMP_next);
        if(KMP_next[len_a_post]==0)
            cout<<0<<endl;
        else{
            cout<<a.substr(0,KMP_next[len_a_post])<<" "<<KMP_next[len_a_post]<<endl;
        }   
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shadandeajian/article/details/81587152