poj--3461 Oulipo -------KMP算法

题目大意:找出匹配串在父串中出现的次数

View Code
 1 #include <iostream>
 2 #include <string.h>
 3 const int MAXN = 1000012;
 4 char a[MAXN],b[MAXN];//a主串 b匹配串
 5 void get_next(char *pstr,int *next)
 6 {
 7     int i=0;
 8     *next=-1;
 9     int j=-1;
10     while(*(pstr+i)!='\0')
11     {
12         if(j==-1||*(pstr+i)==*(pstr+j))
13         {
14             i++;
15             j++;
16             if(*(pstr+i)!=*(pstr+j)) *(next+i)=j;
17             else *(next+i)=*(next+j);
18         }
19         else
20         {
21             j=*(next+j);
22         }
23     }
24     
25 }
26 int index_KMP(char *pstr1,char *pstr2 ,int pos)
27 {
28     int length1=0;
29     int length2=0;
30     int i;
31     int cnt=0;
32     length1=strlen(pstr1);
33     length2=strlen(pstr2);  
34     int j=0;
35     i=pos;
36     int *next;
37     next=new int[length2];
38     get_next(pstr2,next);
39     while(i<length1)
40     {
41         if(*(pstr1+i)==*(pstr2+j)||j==-1)
42         {
43             j++;
44             i++;
45         }
46         else
47         {
48             j=next[j];
49         }
50         if(j==length2) cnt++;
51     }
52     return cnt;
53 }
54 int main(void)
55 {
56     int t;
57     scanf("%d",&t);
58     while(t--)
59     {
60         scanf("%s",b);
61         scanf("%s",a);
62         printf("%d\n",index_KMP(a,b,0));
63     }
64     return 0;
65 }
posted @ 2012-08-22 20:19  Wheat″  阅读(120)  评论(0)    收藏  举报