HDU1711 ——Number Sequence(KMP模板题)
来源:互联网 发布:侠客风云传有mac版吗 编辑:程序博客网 时间:2024/06/10 11:57
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
代码:
#include <iostream>#include <cstdio>using namespace std;int next1[10005];int board[10005];int str[1000005];int N,M;void getNext(){ int k = -1; int j = 0; next1[0] = -1;//next数组最好是从0开始要不然会很麻烦 while(j<M){ if(k == -1 || board[j] == board[k]){ if(board[j+1] == board[k+1]){ next1[++j] = next1[++k]; } else next1[++j] = ++k; } else { k = next1[k]; } }}int Find(){//返回匹配到的位置 getNext(); int temp1 = 0,temp2 = 0; while(temp1<N && temp2<M){ if(temp2 == -1 || str[temp1] == board[temp2]){ temp1++;temp2++; } else{ temp2 = next1[temp2]; } } if(temp2 == M)return temp1-temp2; else return -1; }int main(){ int T; cin>>T; while(T--){ scanf("%d %d",&N,&M); for(int i=0 ; i<N ; i++)scanf("%d",&str[i]); for(int i=0 ; i<M ; i++)scanf("%d",&board[i]);//这里和next数组统一也从0开始 int re = Find(); if(re == -1)printf("-1\n"); else printf("%d\n",re+1);//由于前面是从0开始而题中是从1开始所以这里加1 } return 0;}
阅读全文
0 0
- HDU1711 ——Number Sequence(KMP模板题)
- 【hdu1711】Number Sequence——KMP
- hdu1711——Number Sequence(KMP求位置)
- hdu1711 Number Sequence(KMP)
- hdu1711 Number Sequence(KMP)
- hdu1711--Number Sequence(KMP)
- HDU1711-Number Sequence-KMP算法(模板)
- HDU1711 Number Sequence【机智 or KMP模板】
- Number Sequence hdu1711 KMP
- hdu1711 Number Sequence,KMP
- hdu1711 Number Sequence (KMP)
- hdu1711 Number Sequence---KMP
- Number Sequence HDU1711 (kmp)
- HDU1711-Number Sequence-KMP
- hdu1711 number sequence KMP
- Hdu1711-Number Sequence-【KMP】
- hdu1711 Number Sequence(KMP水题)
- hdu1711 Number Sequence(KMP算法)
- 一文看懂常用的梯度下降算法
- C语言线性表之顺序表
- pageContext--四大作用域对象
- python 读取文件时报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 205: illegal multib
- 【反射】java绝对路径获取文件
- HDU1711 ——Number Sequence(KMP模板题)
- Mybatis-PageHelper
- (4.1.52)Android启动流程分析
- 图结构
- spring提供的可扩展的接口以及类
- cocos2d-x命令行生成项目并编译运行
- 机器学习第四课
- SpringMVC基础
- 2017.12.04 多线程