HDU5918(KMP)

Posted Penn000

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU5918(KMP)相关的知识,希望对你有一定的参考价值。

Sequence I

Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 729    Accepted Submission(s): 277


Problem Description

Mr. Frog has two sequences a1,a2,?,an and b1,b2,?,bm and a number p. He wants to know the number of positions q such that sequence b1,b2,?,bm is exactly the sequence aq,aq+p,aq+2p,?,aq+(m1)p where q+(m1)pn and q1.
 

 

Input

The first line contains only one integer T100, which indicates the number of test cases.

Each test case contains three lines.

The first line contains three space-separated integers 1n106,1m106 and 1p106.

The second line contains n integers a1,a2,?,an(1ai109).

the third line contains m integers b1,b2,?,bm(1bi109).
 

 

Output

For each test case, output one line “Case #x: y”, where x is the case number (starting from 1) and y is the number of valid q’s.
 

 

Sample Input

2
6 3 1
1 2 3 1 2 3
1 2 3
6 3 2
1 3 2 2 3 1
1 2 3
 

 

Sample Output

Case #1: 2
Case #2: 1
 

 

Source

 
 题意:问从a串中每隔p取字,有多少个可与b串匹配
思路:用kmp可计算连续的a串中有多少个b串,可将每p个数字取出组成连续的新串,共可取出p条新串,对每条新串kmp再求和即可
 1 //2016.10.08
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstring>
 5 
 6 using namespace std;
 7 const int N = 1000005;
 8 const int inf = 0x3f3f3f3f;
 9 int a[N], b[N], nex[N],n, m, p;
10 
11 void pre_kmp(int b[], int m)//得到next数组
12 {
13     int i, j;
14     j = nex[0] = -1;
15     i = 0;
16     while(i < m)
17     {
18         while(j != -1 && b[i]!= b[j])j = nex[j];
19         nex[++i] = ++j;
20     }
21 }
22 
23 int kmp(int a[], int n, int b[], int m)
24 {
25     int ans = 0;
26     pre_kmp(b, m);
27     for(int pos = 0; pos < p; pos++)
28     {
29         int i = pos, j = 0;
30         while(i < n)
31         {
32             while(j != -1 && a[i] != b[j])j = nex[j];
33             i += p; j++;
34             if(j >= m){ans++; j = nex[j];}
35         }
36     }
37     return ans;
38 }
39 
40 int main()
41 {
42     int T, kase = 0;
43     scanf("%d", &T);
44     while(T--)
45     {
46         scanf("%d%d%d", &n, &m, &p);
47         for(int i = 0; i < n; i++)scanf("%d", &a[i]);
48         for(int i = 0; i < m; i++)scanf("%d", &b[i]);
49         printf("Case #%d: %d\n", ++kase, kmp(a,n,b,m));
50     }
51 
52     return 0;
53 }

 

以上是关于HDU5918(KMP)的主要内容,如果未能解决你的问题,请参考以下文章

HDU 5918 SequenceI (2016 CCPC长春站 KMP模版变形)

HDU 5918 Sequence I KMP

hdu-5918 Sequence I(kmp)

HDU 5918 Sequence I (KMP)

hdu 5918Sequence I(KMP)

hdu 5918