POJ 3461 (kmp)

来源:互联网 发布:手机淘宝旧版5.2.2 编辑:程序博客网 时间:2024/06/11 02:12






http://poj.org/problem?id=3461








题目大意:

给s1和s2   问s1在s2中出现多少次








分析:

kmp模板题吧   只有真正理解才能做的出来的










AC代码:

#include <iostream>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <math.h>#include <vector>#include <stack>#include <queue>#include <map>#include <set>#include<list>#include <bitset>#include <climits>#include <algorithm>#define gcd(a,b) __gcd(a,b)#define mset(a,n) memset(a,n,sizeof(a))#define FINfreopen("input.txt","r",stdin)#define FOUT freopen("output.txt","w",stdout)typedef long long LL;const LL mod=1e9+7;const int INF=0x3f3f3f3f;const double PI=acos(-1.0);using namespace std;int next[1000010];char str1[1000010];char str2[1000010];int sum;void get_next(char *str){    int n=strlen(str);    int j=-1;    next[0]=-1;    for (int i=1;i<n;i++){        while (j>=0&&str[i]!=str[j+1]) j=next[j];        if (str[i]==str[j+1]) j++;        next[i]=j;    }}void KMP(char *str2,char *str1){    get_next(str2);    int len1=strlen(str1);    int len2=strlen(str2);    int j=-1;    for (int i=0;i<len1;i++){        while (j>=0&&str1[i]!=str2[j+1]) j=next[j];        if (str1[i]==str2[j+1]) j++;        if (j==len2-1) sum++,j=next[j];    }}int main (){    int t;   // FIN;    scanf ("%d",&t);    while (t--){        scanf ("%s%s",str2,str1);        sum=0;        KMP(str2,str1);        printf ("%d\n",sum);    }    return 0;}


原创粉丝点击