您的位置:首页 > 其它

FOJ 1481 环串

2009-08-04 16:08 232 查看
http://acm.fzu.edu.cn/problem.php?pid=1481

解题思路:这道题也是要用到KMP算法,题目给你的串是首尾相连的,所以就想到要把环串放大2倍,模式串放大一倍,匹配就+1,最后输出count.

#include <stdio.h>
#include <string.h>
#define clen 402

void GetNext(char t[],int next[])
{
int i=0,j=-1;
next[0] = -1;
while (t[i+1]!='/0')
{
if (j == -1||t[i] == t[j])
{
i++;
j++;
if(t[i]!=t[j])
next[i] = j;
else
next[i] = next[j];
}
else
j = next[j];
}
}

bool KMPIndex(char s[],char t[])
{
int next[clen];
int i=0,j=0;
GetNext(t,next);
int tlen = strlen(t);
int slen = strlen(s);
while (i<slen&&j<tlen)
{
if (j == -1||s[i] == t[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j>=tlen)
{
return true;
}
else
return false;
}

int main()
{
char s[602],t[clen],k[clen];
int i;
int count;/*统计匹配的字符串个数*/
int NumOfStrings;
while (scanf("%s",&s)!=EOF)
{
strcpy(t,s);
strcat(s,t);
strcat(s,t);
count = 0;
scanf("%d",&NumOfStrings);
for (i=0;i<NumOfStrings;i++)
{
scanf("%s",t);
strcpy(k,t);
strcat(t,k);
if (KMPIndex(s,t))
count++;
}
printf("%d/n",count);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: