首页 > 代码库 > hdu[1711]number sequence
hdu[1711]number sequence
Problem Description
Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.
Input
The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], ...... , a[N]. The third line contains M integers which indicate b[1], b[2], ...... , b[M]. All integers are in the range of [-1000000, 1000000].
Output
For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
Sample Input
213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
Sample Output
6-1
Solution
kmp模版题目
#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;inline int read(){ int x=0,c=getchar(),f=1; for(;c<48||c>57;c=getchar()) if(!(c^45)) f=-1; for(;c>47&&c<58;c=getchar()) x=(x<<1)+(x<<3)+c-48; return x*f;}int sub_l,tar_l,sub[10001],tar[1000001],p[10001];inline void pre(){ for(int i=2,j=0;i<=sub_l;i++){ while(j&&sub[j+1]^sub[i]) j=p[j]; if(!(sub[j+1]^sub[i])) j++; p[i]=j; }}inline void kmp(){ int ans=-1; for(int i=1,j=0;i<=tar_l;i++){ while(j&&sub[j+1]^tar[i]) j=p[j]; if(!(sub[j+1]^tar[i])) j++; if(!(j^sub_l)){ ans=i-sub_l+1; break; } } printf("%d\n",ans);}int main(){ int T=read(); while(T--){ tar_l=read(),sub_l=read(); memset(p,0,sizeof(p)); for(int i=1;i<=tar_l;i++) tar[i]=read(); for(int j=1;j<=sub_l;j++) sub[j]=read(); pre(); kmp(); } return 0;}
hdu[1711]number sequence
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。