[HDU5918]Sequence I
Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Problem Description Mr. Frog has two sequences and and a number . He wants to know the number of positions q such that sequence is exactly the sequence where and .
Input The first line contains only one integer , which indicates the number of test cases.
Each test case contains three lines.
The first line contains three space-separated integers and .
The second line contains n integers .
the third line contains m integers .
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
題意: 給,再給兩個數字串,的長度為,的長度為。問有多少個滿足 與 完全一致 題解: kmp,把中的元素按照歸類,然後對於每個類當成一個串來用kmp統計這個串中有多少個與完全一致的子串。 注意:用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;
}