HDU 5918(KMP)
傳送門
題面:
Mr. Frog has two sequences a1,a2,⋯,ana1,a2,⋯,an and b1,b2,⋯,bmb1,b2,⋯,bm and a number p. He wants to know the number of positions q such that sequence b1,b2,⋯,bmb1,b2,⋯,bm is exactly the sequence aq,aq+p,aq+2p,⋯,aq+(m−1)paq,aq+p,aq+2p,⋯,aq+(m−1)p where q+(m−1)p≤nq+(m−1)p≤n and q≥1q≥1.
Input
The first line contains only one integer T≤100T≤100, which indicates the number of test cases.
Each test case contains three lines.
The first line contains three space-separated integers 1≤n≤106,1≤m≤1061≤n≤106,1≤m≤106 and 1≤p≤1061≤p≤106.
The second line contains n integers a1,a2,⋯,an(1≤ai≤109)a1,a2,⋯,an(1≤ai≤109).
the third line contains m integers b1,b2,⋯,bm(1≤bi≤109)b1,b2,⋯,bm(1≤bi≤109).
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的陣列A,和一個長度為m的陣列B,以及一個引數p,問你至少有多少個p使得,ap,ap+q,ap+2q....ap+(m-1)*q恰好為陣列B。
題目分析:
因為考慮到是要求出一個數組中是否存在某個子序列為另一個序列,因此我們不難想到可以用KMP進行解決。而在這個題目中,因為需要考慮跨p-1個數字後是否匹配,因此我們只需在做kmp匹配的過程中,將模式串的下標都加上p即可。(同時注意每一個位置都需要進行延申匹配,共進行p次匹配)
程式碼:
#include <bits/stdc++.h>
#define maxn 1000005
using namespace std;
int a[maxn],b[maxn];
int nex[maxn];
int n,m,p;
void get_next(int *x){//獲取next陣列
int i,j;
nex[0]=j=-1;
i=0;
while(i<m){
while(j!=-1&&x[i]!=x[j]) j=nex[j];
nex[++i]=++j;
}
}
int kmp(int *x,int *y){//kmp匹配
get_next(x);
int i,j;
int ans=0;
for(int k=0;k<p;k++){//注意需要匹配p次
i=k,j=0;
while(i<n){
while(j!=-1&&y[i]!=x[j]) j=nex[j];
i+=p,j++;
if(j>=m) ans++,j=nex[j];
}
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
int cntt=0;
while(t--){
int cnt=0;
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]);
int res=kmp(b,a);
printf("Case #%d: %d\n",++cntt,res);
}
return 0;
}