FOJ 1481 环串

 

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); } }

你可能感兴趣的:(FOJ 1481 环串)