UVALive5876-Writings on the Wall-KMP

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

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

#include <cstdio>
#include <cstring>
#include <algorithm> using namespace std; const int maxn = ; int T;
int next[maxn];
char s1[maxn],s2[maxn],s[maxn]; int getnext(char T[],int m)
{
int i=,j=-;
next[] = -;
while(i < m)
{
if(j == - || T[j] == T[i])
{
i++;j++;
next[i] = j;
}
else
j = next[j];
}
} int main()
{
scanf("%d",&T);
for(int i=;i<T;i++)
{
scanf("%s%s",s1,s2); int l1 = strlen(s1),l2 = strlen(s2);
for(int i=;i<l2;i++) s[i] = s2[i];
s[l2] = '~';
for(int i=l2+;i<l2+l1+;i++) s[i] = s1[i-l2-];
s[l1+l2+] = '\0'; int len = l1+l2+;
getnext(s,len); int ans = ,p=len;
while(next[p] != -)
{
ans++;
p = next[p];
}
printf("%d\n",ans);
}
}
上一篇:window系统 查看端口 被哪个进程占用了


下一篇:判断是否是IE9浏览器的最短语句 var ie=!-[1,]