1. 程式人生 > >[HDU5918]Sequence I

[HDU5918]Sequence I

Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)

Problem Description Mr. Frog has two sequences a1,a2,,ana_1,a_2,⋯,a_n and b1,b2,,bmb_1,b_2,⋯,b_m and a number pp. He wants to know the number of positions q such that sequence b1,b2,,bmb_1,b_2,⋯,b_m

is exactly the sequence aq,aq+p,aq+2p,,aq+(m1)pa_q,a_{q+p},a_{q+2p},⋯,a_{q+(m−1)p} where q+(m1)pnq+(m−1)p≤n and q1q≥1.

Input The first line contains only one integer T100T≤100, which indicates the number of test cases.

Each test case contains three lines.

The first line contains three space-separated integers 1n106,1m1061≤n≤10^6,1≤m≤10^6 and 1p1061≤p≤10^6.

The second line contains n integers a1,a2,,an(1ai109)a_1,a_2,⋯,a_n(1≤a_i≤10^9).

the third line contains m integers b1,b2,,bm(1bi109)b_1,b_2,⋯,b_m(1≤b_i≤10^9)

.

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

題意:n,m,pn,m,p,再給兩個數字串a,ba,baa的長度為nnbb的長度為mm。問有多少個q>=1q>=1滿足 b1,b2,,bmb_1,b_2,⋯,b_maq,aq+p,aq+2p,,aq+(m1)pa_q,a_{q+p},a_{q+2p},⋯,a_{q+(m−1)p} 完全一致 題解: kmp,把aa中的元素按照ii%p歸類,然後對於每個類當成一個串來用kmp統計這個串中有多少個與bb完全一致的子串。 注意:用kmp統計符合條件的子串個數的時候,每匹配到一個子串就要將指標向下移動一格。不然會重複計算。

#include<bits/stdc++.h>
#define LiangJiaJun main
#define MOD 19991227
using namespace std;
int n,m,p;
int a[1000004],b[1000004],nt[1000004];
vector<int>ov[1000004];
int getnext(){
    memset(nt,0,sizeof(nt));
    int j=0;
    for(int i=2;i<=m;i++){
        while(j>0&&b[j+1]!=b[i])j=nt[j];
        if(b[j+1]==b[i])j++;
        nt[i]=j;
    }
    return 0;
}
int calc(int st){
    int j=0,res=0;
    for(int i=0;i<ov[st].size();i++){
        while(j>0&&b[j+1]!=ov[st][i])j=nt[j];
        if(b[j+1]==ov[st][i])j++;
        if(j==m){
            res++;
            j=nt[j];///記住要後移
        }
    }
    return res;
}
int w33ha(int CASE){
    scanf("%d%d%d",&n,&m,&p);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    for(int i=1;i<=m;i++)scanf("%d",&b[i]);
    getnext();
    for(int i=0;i<p;i++)if(ov[i].size()>0)ov[i].clear();
    for(int i=1;i<=n;i++)ov[i%p].push_back(a[i]);
    int ans=0;
    for(int i=0;i<p;i++){
        if(ov[i].size()>=m)ans+=calc(i);
    }
    printf("Case #%d: %d\n",CASE,ans);
    return 0;
}
int LiangJiaJun(){
    int T;scanf("%d",&T);
    for(int i=1;i<=T;i++)w33ha(i);
    return 0;
}