HDU2087剪花布条(KMP)

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=2087

就是给你一个串和一个模式串,问,这个串中有多少个模式串。

就是KMP啦,稍微修改一下就是匹配成功后返回匹配成功后的最后一个字符的位置的后一位,而不是第一位。因为是剪纸啦,不能剪过的再剪一次是吧。。

 1 #include<stdio.h>
 2 #include<string.h>
 3 int next[1005];
 4 void get_next(char t[1005])
 5 {
 6     int i=0,j=-1,len;
 7 next[0]=-1;
 8     len=strlen(t);
 9     while(i<len)
10     {
11         if(j==-1||t[i]==t[j])
12         {++i;
13         ++j;
14         next[i]=j;
15         }
16         else j=next[j];
17     }
18 }
19 int index_kmp(char s[1005],char t[1005],int pos)
20 {
21     int i=pos,j=0,lens,lent,sum;
22     lens=strlen(s);
23     lent=strlen(t);
24     sum=0;
25     while(i<lens&&j<lent)
26     {
27         if(j==-1||s[i]==t[j])
28         { ++i;++j;}
29         else j=next[j];
30     }
31     if(j>=lent) return i;
32     else return 0;
33 }
34 int main()
35 {
36     char t[1005],s[1005],ch,f,len;
37     int i,sum;
38     scanf("%s",s);
39     while(s[0]!='#')
40     {
41         scanf("%s",t);
42         i=0;
43         len=strlen(s);
44         get_next(t);
45         sum=0;f;
46         while(i<len)
47         {
48         f=index_kmp(s,t,i);
49         if(f!=0){sum++;i=f;}
50         else break;
51         }
52         printf("%d\n",sum);
53           gets(s);
54           scanf("%s",s);
55           ch=getchar();
56         
57     }
58 
59 
60 
61 
62 
63   return 0;
64 }

 

posted @ 2013-04-17 18:48  Yuki_i  阅读(253)  评论(0编辑  收藏  举报