A - Number Sequence HDU-1711

题意:

      反正就是给出一个T,然后每个T:一个n,一个m,表示主串的数字数量和模式串的数字数量,求第一个匹配的位置。

思路:

     KMP模板套套就好啦。

参考代码:

 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 int nextt[10005];
21 int a[1000005];
22 int b[10005];
23 int n,m;
24 void findnext()
25 {
26     memset(nextt,0,sizeof(nextt));
27     int len=m;
28     nextt[0]=-1;
29     int k=-1,j=0;
30     while(j<len)
31     {
32         if(k==-1||b[k]==b[j])
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         {
43             k=nextt[k];
44         }
45     }
46 }
47 
48 int kmp()
49 {
50     int i=0,j=0;
51     int sa=n,sb=m;
52     while(i<sa&&j<sb)
53     {
54         if(j==-1||a[i]==b[j])
55         {
56             i++;
57             j++;
58         }
59         else
60         {
61             j=nextt[j];
62         }
63     }
64     if(j==sb)
65         return i-j+1;
66     else
67         return -1;
68 }
69 int main()
70 {
71     int t;
72     scanf("%d",&t);
73     while(t--)
74     {
75         scanf("%d%d",&n,&m);
76         for(int i=0;i<n;i++)
77         {
78             scanf("%d",&a[i]);
79         }
80         for(int j=0;j<m;j++)
81             scanf("%d",&b[j]);
82         findnext();
83         int res=kmp();
84         printf("%d\n",res);
85 
86     }
87     return 0;
88 }
View Code

 

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值