链接:戳这里
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,⋯,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
题意:
分别给出长度为n,m的正整数序列a,b,要求b序列去匹配a序列且间隔为p,然后找出有多少个这样的起点q
思路:
间隔为p的话显然就拆成p个串去匹配统计贡献
对于每个拿出来的s串与b串做KMP操作
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int f[2000100];
void getf(int *p,int m){
int j=0;
f[0]=f[1]=0;
for(int i=1;i<m;i++){
j=f[i];
while(j && p[j]!=p[i]) j=f[j];
if(p[i]==p[j]) f[i+1]=j+1;
else f[i+1]=0;
}
}
int KMP(int *s,int *p,int n,int m){
int num=0;
int j=0;
for(int i=0;i<n;i++){
while(j && p[j]!=s[i]) j=f[j];
if(s[i]==p[j]) j++;
if(j==m) num++;
}
return num;
}
int s[2000100],p[2000100],t[2000100];
int n,m,P;
int main(){
int T;
scanf("%d",&T);
for(int cas=1;cas<=T;cas++){
scanf("%d%d%d",&n,&m,&P);
memset(t,0,sizeof(t));
memset(p,0,sizeof(p));
for(int i=0;i<n;i++) scanf("%d",&t[i]);
for(int i=0;i<m;i++) scanf("%d",&p[i]);
getf(p,m);
int ans=0;
for(int i=0;i<P;i++){
int num=0;
for(int j=i;j<n&&i+(m-1)*P<n;j+=P){
s[num++]=t[j];
}
///for(int j=0;j<num;j++) cout<<s[j]<<" ";cout<<endl;
ans+=KMP(s,p,num,m);
}
printf("Case #%d: %d\n",cas,ans);
}
return 0;
}