首页 > 代码库 > hdu-5918 Sequence I(kmp)
hdu-5918 Sequence I(kmp)
题目链接:
Sequence I
Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 687 Accepted Submission(s): 262
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).
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
26 3 11 2 3 1 2 31 2 36 3 21 3 2 2 3 11 2 3
Sample Output
Case #1: 2
Case #2: 1
题意:
问a数组里面匹配的b有多少个;
思路:
把a里面间隔p的拿出来,然后用b数组跑kmp求;
AC代码:
#include <bits/stdc++.h>using namespace std;const int maxn=1e6+10;int n,m,p,a[maxn],b[maxn],c[maxn],nex[maxn];inline void makenext(){ int k=-1,j=0;nex[0]=-1; while(j<m) { if(k==-1||b[j]==b[k]) { j++;k++; nex[j]=k; } else k=nex[k]; }}inline int kmp(int l){ int pb=0,pc=0,ans=0; while(pb<m&&pc<l) { if(pb==-1||b[pb]==c[pc])pb++,pc++; else pb=nex[pb]; if(pb==m)ans++,pb=nex[pb]; } return ans;}int main(){ int t,Case=0; scanf("%d",&t); while(t--) { 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]); makenext(); int ans=0; for(int i=0;i<p;i++) { int cnt=0; for(int j=i;j<n;j+=p)c[cnt++]=a[j]; ans+=kmp(cnt); } printf("Case #%d: %d\n",++Case,ans); } return 0;}
hdu-5918 Sequence I(kmp)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。