首页 > 代码库 > hdu-5918 Sequence I(kmp)

hdu-5918 Sequence I(kmp)

题目链接:

Sequence I

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


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
26 3 11 2 3 1 2 31 2 36 3 21 3 2 2 3 11 2 3
 

 

Sample Output
Case #1: 2
Case #2: 1
 
题意:
 
问a数组里面匹配的b有多少个;
 
思路:
 
把a里面间隔p的拿出来,然后用b数组跑kmp求;
 
AC代码:
 
#include <bits/stdc++.h>using namespace std;const int maxn=1e6+10;int n,m,p,a[maxn],b[maxn],c[maxn],nex[maxn];inline void makenext(){    int k=-1,j=0;nex[0]=-1;    while(j<m)    {        if(k==-1||b[j]==b[k])        {            j++;k++;            nex[j]=k;        }        else k=nex[k];    }}inline int kmp(int l){    int pb=0,pc=0,ans=0;    while(pb<m&&pc<l)    {        if(pb==-1||b[pb]==c[pc])pb++,pc++;        else pb=nex[pb];        if(pb==m)ans++,pb=nex[pb];    }    return ans;}int main(){    int t,Case=0;    scanf("%d",&t);    while(t--)    {        scanf("%d%d%d",&n,&m,&p);        for(int i=0;i<n;i++)scanf("%d",&a[i]);        for(int i=0;i<m;i++)scanf("%d",&b[i]);        makenext();        int ans=0;        for(int i=0;i<p;i++)        {            int cnt=0;            for(int j=i;j<n;j+=p)c[cnt++]=a[j];            ans+=kmp(cnt);        }        printf("Case #%d: %d\n",++Case,ans);    }        return 0;}

  

hdu-5918 Sequence I(kmp)