B - Oulipo HDU-1686

题目大意:

    给一个t,接下来每个t两个串,求能匹配的次数。

解题思路:

    修改模板kmp,不要j==len就结束while,而是在i==len才结束,由于这里是可重叠的匹配,所以 j==len时,j=next[j],ans++。

参考代码:

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <map>
 4 #include <string>
 5 #include <queue>
 6 #include <stack>
 7 #include <set>
 8 #include <algorithm>
 9 
10 #include <cstdio>
11 #include <cstring>
12 #include <cmath>
13 #include <cstdlib>
14 using namespace std;
15 
16 const int INF=0x3f3f3f3f;
17 const int SIZE=10000;
18 typedef long long LL;
19 
20 char a[1000005];
21 char b[10005];
22 int nextt[10005];
23 
24 void nexxt()
25 {
26     memset(nextt,0,sizeof(nextt));
27     int j=0,k=-1;
28     nextt[0]=-1;
29     int len=strlen(b);
30     while(j<len)
31     {
32         if(k==-1||b[j]==b[k])
33         {
34             ++k;
35             ++j;
36             if(b[j]!=b[k])
37                 nextt[j]=k;
38             else
39                 nextt[j]=nextt[k];
40         }
41         else
42             k=nextt[k];
43     }
44 }
45 
46 int kmp()
47 {
48     int i=0,j=0,ans=0;
49     int la=strlen(a),lb=strlen(b);
50     while(i<la)
51     {
52         //printf("i:%d j:%d\n",i,j);
53         if(j==-1||a[i]==b[j])
54         {
55             i++;
56             j++;
57         }
58         else
59             j=nextt[j];
60         if(j==lb)
61         {
62             j=nextt[j];
63             ans++;
64         }
65     }
66     return ans;
67 
68 }
69 
70 int main()
71 {
72     int t;
73     scanf("%d",&t);
74     getchar();
75     while(t--)
76     {
77          gets(b);
78          gets(a);
79          nexxt();
80          printf("%d\n",kmp());
81     }
82     return 0;
83 }
View Code

 

转载于:https://www.cnblogs.com/xxQ-1999/p/7522478.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值