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+(m−1)p where q+(m−1)p≤n and q≥1.
Input
The first line contains only one integer T≤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≤106 and 1≤p≤106.
The second line contains n integers a1,a2,⋯,an(1≤ai≤109).
the third line contains m integers 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
Source
2016中国大学生程序设计竞赛(长春)-重现赛
问有多少个q,能让b1,b2,⋯,bm等于 aq,aq+p,aq+2p,⋯,aq+(m−1)p.
KMP做法。我们可以将A串划分成p个子串,起始位置分别为0~p-1,在KMP计算这样的子串中有多少能与B串匹配的子串。。。
暴力做法。(暴力啊,暴力的时间与KMP的时间居然差不多。。)
KMP
#include<bits/stdc++.h>
using namespace std;
int a[1000006],b[1000006];
int c[1000006];
int n,m,p;
int Next[1000006];
void get_next(int b[],int m){
int i=0,j=-1;
Next[0]=-1;
while(i<m){
if(j==-1||b[i]==b[j]){
i++,j++;
Next[i]=j;
}
else j=Next[j];
}
}
int KMP(int a[],int n,int b[],int m){
int i=0,j=0;
int num=0;
while(i<n){
if(j==-1||a[i]==b[j]){
i++,j++;
if(j==m){
j=Next[j];
num++;
}
}
else j=Next[j];
}
return num;
}
int main(){
int t;
scanf("%d",&t);
for(int cas=1;cas<=t;cas++){
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 ans=0;
get_next(b,m);
for(int i=0;i<p;i++){
int xia=0;
for(int j=i;j<n;j+=p) c[xia++]=a[j];
ans+=KMP(c,xia,b,m);
}
printf("Case #%d: %d\n",cas,ans);
}
return 0;
}
暴力
#include<bits/stdc++.h>
using namespace std;
int a[1000006],b[1000006];
int n,m,p;
bool judge(int s){
for(int i=1;i<=m;i++){
if(s>n) return false;
if(b[i]==a[s]) s+=p;
else return false;
}
return true;
}
int main(){
int t;
scanf("%d",&t);
for(int cas=1;cas<=t;cas++){
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]);
int ans=0;
for(int i=1;i<=n;i++){
if(judge(i)==true) ans++;
}
printf("Case #%d: %d\n",cas,ans);
}
return 0;
}