UVALive5876-Writings on the Wall-KMP

有两段字符串,第一段的尾和第二段的头可能重合。问有多少种组合的可能。

需要理解一下next数组的意义。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 100100;

int T;
int next[maxn];
char s1[maxn],s2[maxn],s[maxn];

int getnext(char T[],int m)
{
    int i=0,j=-1;
    next[0] = -1;
    while(i < m)
    {
        if(j == -1 || T[j] == T[i])
        {
            i++;j++;
            next[i] = j;
        }
        else
            j = next[j];
    }
}

int main()
{
    scanf("%d",&T);
    for(int i=0;i<T;i++)
    {
        scanf("%s%s",s1,s2);

        int l1 = strlen(s1),l2 = strlen(s2);
        for(int i=0;i<l2;i++) s[i] = s2[i];
        s[l2] = '~';
        for(int i=l2+1;i<l2+l1+1;i++) s[i] = s1[i-l2-1];
        s[l1+l2+1] = '';

        int  len = l1+l2+1;
        getnext(s,len);


        int ans = 0,p=len;
        while(next[p] != -1)
        {
            ans++;
            p = next[p];
        }
        printf("%d
",ans);
    }
}
原文地址:https://www.cnblogs.com/helica/p/5196835.html