POJ 3461 Oulipo

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

题目大意 以A为子串,查找B中有几个A。

思路。KMP算法

View Code
 1 #include<stdio.h>

 2 #include<string.h>

 3 #define N 1000001

 4 int nextt[N];

 5 char str1[N],str2[N];

 6 void next(char s[])

 7  {

 8      int i=1,j=0;

 9      int len=strlen(s);

10      nextt[0]=-1;

11      while(i<len)

12      {

13          if(j==-1||s[i]==s[j])

14          {

15              ++i;

16              ++j;

17              if(s[i]!=s[j])

18                  nextt[i]=j;

19              else

20                  nextt[i]=nextt[j];

21          }

22          else

23              j=nextt[j];

24      }

25  }

26  int kmp(char ss[],char s[])

27  {

28      int len1=strlen(ss);

29      int len2=strlen(s);

30      next(s);

31      int i=0,j=0,n=0;

32      while(i<len1)

33      {

34          if(j==-1||ss[i]==s[j])

35          {

36              ++i;

37              ++j;

38          }

39          else

40              j=nextt[j];

41    if(j==len2)

42          n++;

43      }

44   return n;

45  }

46  int main()

47  {

48   int i,t;

49   scanf("%d%*c",&t);

50   while(t--)

51   {

52    gets(str1);

53    gets(str2);

54    int s=0;

55    s=kmp(str2,str1);

56    printf("%d\n",s);

57   }

58      return 0;

59  }

你可能感兴趣的:(poj)