poj3461 Oulipo

题目链接:http://poj.org/problem?id=3461

题意就是求模式串在一个主串中出现的次数

KMP的简单应用

代码:

 1 #include<cstring>
 2 #include<cstdlib>
 3 #include<cstdio>
 4 #include<iostream>
 5 using namespace std;
 6 #define maxn 1000100
 7 int f[maxn];
 8 char s1[maxn];
 9 char s2[maxn];
10 int n,m;
11 void callfail()
12 {
13    int i,j=0,k=-1;
14    f[0]=-1;
15    while(j<n)
16    {
17        if(k==-1||s1[j]==s1[k])
18                k++,j++,f[j]=k;
19        else k=f[k];
20    }
21 }
22 int  count_words()
23 {
24      int i=0,j=0,ans=0;
25      while(i<n&&j<m)
26      {
27       if(i==-1||s1[i]==s2[j]) 
28       {
29           i++;j++;
30           if(i==n)
31           {
32                   ans++;
33                   i=f[i];
34           }
35       }
36       else 
37          i=f[i];
38      }
39      return ans;
40 }
41 int main()
42 {
43        int t;
44        scanf("%d",&t);
45        while(t--)
46        {
47            scanf("%s%s",s1,s2);
48            n=strlen(s1);
49            m=strlen(s2);
50            memset(f,0,sizeof(f));
51            callfail();
52            int ans=count_words();
53            cout<<ans<<endl;
54 
55        }
56        return 0;
57 }
View Code

 

posted on 2013-08-25 22:35  GyyZyp  阅读(150)  评论(0编辑  收藏  举报

导航