hdu 1711 kuangbin 字符串 A KMP入门
来源:互联网 发布:汤神君没有朋友知乎 编辑:程序博客网 时间:2024/06/05 11:19
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
2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1
Sample Output
6
-1
题解:
KMP入门。
注意此题数据很多。应用Scanf,cin会超时。
但是用scanf就不能定义为字符数组,这个需要注意。
代码:
#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn = 1000000+100;const int maxm = 10000+100;int nt[maxn];int S[maxn],T[maxm];int slen,tlen;void getNext(){ int j,k; j=0;k=-1;nt[0]=-1; while(j<tlen) { if(k==-1||T[j]==T[k]) { nt[++j] = ++k; } else { k=nt[k]; } } return ;}int indexKMP(){ int i=0; int j=0; getNext(); while(i<slen&&j<tlen) { if(j==-1||S[i]==T[j]) { i++; j++; } else { j=nt[j]; } } if(j==tlen) { return i-tlen; } else { return -1; }}int main(){ int ks; cin>>ks; while(ks--) { int n,m; scanf("%d%d",&n,&m); for(int i=0;i<n;i++) { scanf("%d",&S[i]); } for(int i=0;i<m;i++) { scanf("%d",&T[i]); } slen = n; tlen = m; int ans = indexKMP(); if(ans==-1) { cout<<-1<<endl; } else { cout<<ans+1<<endl; } } return 0;}
- hdu 1711 kuangbin 字符串 A KMP入门
- [kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher A HDU 1711
- 字符串 KMP HDU 1711
- HDU 1711 kmp入门
- kuangbin kmp专题中的字符串暴力
- kmp 入门题(hdu 1711)
- HDU 1711 KMP算法入门
- HDU 1867 A + B for you again 字符串拼接 kmp
- hdu 1711 KMP算法,字符串匹配
- HDU - 1711 Number Sequence KMP字符串匹配
- 【KMP字符串匹配】hdu 1711 Number Sequence
- HDU 1711(KMP)字符串匹配
- HDU 1711 Number Sequence(KMP入门)
- HDU 1711 Number Sequence KMP入门
- HDU-1711 Number Sequence(kmp入门)
- hdu 1711 Number Sequence KMP入门题
- HDU 1711:Number Sequence (KMP入门)
- 字符串 KMP入门,讲解
- ABP从入门到精通(6):快速重命名解决方案
- CODEVS--1206 保留两位小数
- 【cf492】E. Vanya and Field(拓展欧几里得)
- macos pip install 一直报错的解决方法
- 3. Longest Substring Without Repeating Characters
- hdu 1711 kuangbin 字符串 A KMP入门
- 普通类中不创建对象,直接写object的方法
- python3.5《机器学习实战》学习笔记(二):k近邻算法实战
- 494. Target Sum
- 【matlab】利用matlab在图形中绘制箭头、标注、圈圈
- Java设计模式之外观模式
- shellapi.h(55) : error C2065: 'HDROP' : undeclared identifier
- jar打成exe文件
- python 学习while语句中的break&continue