Oulipo__poj3461__kmp

 1 #include<cstdio>

 2 #include<cstring>

 3 const int maxm=1e4+5;

 4 const int maxn=1e6+5;

 5 char p[maxm];

 6 char t[maxn];

 7 int f[maxm];

 8 int ans;

 9 void getfail()

10 {

11     int m=strlen(p);

12     f[0]=f[1]=0;

13     for(int i=1;i<m;i++){

14        int j=f[i];

15        while(j&&p[j]!=p[i])

16             j=f[j];

17        f[i+1]=p[j]==p[i]?j+1:0;

18     }

19 }

20 void kmp()

21 {

22     int m=strlen(p);

23     int n=strlen(t);

24     getfail();

25     int j=0;

26     for(int i=0;i<n;i++){

27         while(j&&p[j]!=t[i])

28             j=f[j];

29         if(p[j]==t[i])

30             j++;

31         if(j==m){

32             ans++;

33         }

34     }

35 }

36 int main()

37 {

38     int test;

39     scanf("%d",&test);

40     while(test--){

41         scanf("%s",&p);

42         scanf("%s",&t);

43         ans=0;

44         kmp();

45         printf("%d\n",ans);

46     }

47     return 0;

48 }
View Code

 

你可能感兴趣的:(poj)