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_na1,a2,⋯,an and b1,b2,⋯,bmb_1,b_2,⋯,b_mb1,b2,⋯,bm and a number ppp. He wants to know the number of positions q such that sequence b1,b2,⋯,bmb_1,b_2,⋯,b_mb1,b2,⋯,bm is exactly the sequence aq,aq+p,aq+2p,⋯,aq+(m−1)pa_q,a_{q+p},a_{q+2p},⋯,a_{q+(m−1)p}aq,aq+p,aq+2p,⋯,aq+(m−1)p where q+(m−1)p≤nq+(m−1)p≤nq+(m−1)p≤n and q≥1q≥1q≥1.
Input
The first line contains only one integer T≤100T≤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≤10^6,1≤m≤10^61≤n≤106,1≤m≤106 and 1≤p≤1061≤p≤10^61≤p≤106.
The second line contains n integers a1,a2,⋯,an(1≤ai≤109)a_1,a_2,⋯,a_n(1≤a_i≤10^9)a1,a2,⋯,an(1≤ai≤109).
the third line contains m integers b1,b2,⋯,bm(1≤bi≤109)b_1,b_2,⋯,b_m(1≤b_i≤10^9)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,pn,m,pn,m,p,再给两个数字串a,ba,ba,b,aaa的长度为nnn,bbb的长度为mmm。问有多少个q>=1q>=1q>=1满足 b1,b2,⋯,bmb_1,b_2,⋯,b_mb1,b2,⋯,bm 与 aq,aq+p,aq+2p,⋯,aq+(m−1)pa_q,a_{q+p},a_{q+2p},⋯,a_{q+(m−1)p}aq,aq+p,aq+2p,⋯,aq+(m−1)p 完全一致
题解:
kmp,把aaa中的元素按照ii%pi归类,然后对于每个类当成一个串来用kmp统计这个串中有多少个与bbb完全一致的子串。
注意:用kmp统计符合条件的子串个数的时候,每匹配到一个子串就要将指针向下移动一格。不然会重复计算。
#include<bits/stdc++.h>
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 main(){
int T;scanf("%d",&T);
for(int i=1;i<=T;i++)w33ha(i);
return 0;
}

本文介绍了一种使用KMP算法解决特定序列匹配问题的方法,通过将长序列按步长归类,针对每一类应用KMP算法统计与目标序列完全一致的子串数量,有效避免了重复计算。

384

被折叠的 条评论
为什么被折叠?



