[kmp] hdu1711 字符串匹配模板
来源:互联网 发布:linux退出文件夹命令 编辑:程序博客网 时间:2024/05/29 10:15
Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 13568 Accepted Submission(s): 6096
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
Source
HDU 2007-Spring Programming Contest
题意:裸的模式匹配问题,N值较大,必须使用线性算法,考虑上KMP。
关于KMP:
好久之前就看过KMP不过一直没搞懂,最近就要比赛,所以临时补一补,翻看了严蔚敏老师的数据结构,研究了许久,算是对KMP略知一二了吧,其KMP主算法还是比较好理解来的(不回溯主串匹配指针,当失配时,利用已经匹配的部分串的信息,使模式串指针向前移动,然后继续匹配),关键在于NEXT数组的求法,其实也不算很难理解(一个递推关系+自匹配的过程),书上后面说的那个修正NEXT数组的求法也比较好理解(当P[i]=P[Next[i]]时,此次滑动的没有作用的,所以直接滑到下一次去)。
#include <iostream>#include<cstdio>#include<cstring>#define _match(a,b) ((a)==(b))using namespace std;int M[10005];int N[1000005];int Mlength;int Nlength;int T;int kmp(int ls,int* str,int lp,int* pat){ int fail[10005]={-1}; int i=0,j; for(j=1;j<lp;j++) { for(i = fail[j-1]; i>=0 && !_match(pat[i+1],pat[j]); i =fail[i]); fail[j] = (_match(pat[i+1],pat[j])?i+1:-1); } for(i=j=0;i<ls&&j<lp;i++) if(_match(str[i],pat[j])) j++; else if (j) j = fail[j-1]+1,i--; return j == lp?(i-lp+1):-1;}int main(){ cin>>T; while(T--) { cin>>Nlength>>Mlength; for(int i = 0; i<Nlength; i++) scanf("%d",&N[i]); for(int i = 0; i<Mlength; i++) scanf("%d",&M[i]); int temp =kmp(Nlength,N,Mlength,M); cout<<temp<<endl; } return 0;}
0 0
- [kmp] hdu1711 字符串匹配模板
- HDU1711 Number Sequence(字符串匹配KMP)
- hdu1711 KMP模板
- HDU1711 模板题-KMP
- hdu1711 KMP模板
- kmp模板 hdu1711
- 【字符串】KMP匹配模板
- 【模板】KMP字符串匹配
- [模板]-KMP字符串匹配
- 字符串匹配 KMP算法 模板
- 字符串匹配(KMP模板题)
- 数据结构-字符串匹配kmp模板
- P3375 【模板】KMP字符串匹配
- 字符串匹配 KMP(模板)
- P3375 【模板】KMP字符串匹配
- kmp-洛谷P3375 【模板】KMP字符串匹配
- hdu1711-Number Sequence-kmp基础 模式匹配
- HDU1711-Number Sequence-KMP算法(模板)
- Android再按一次后退键退出应用程序
- C++深拷贝与浅拷贝
- 代码生成器,极大简化你的工作
- IOS开发之MPMoviePlayerController
- HDU1905 Pseudoprime numbers(搜索)
- [kmp] hdu1711 字符串匹配模板
- 数据库优化
- Android handler的警告Handler Class Should be Static or Leaks Occur
- AndroidManifest.xml——文件详解(三)
- 高性能mysql笔记---mysql架构[-1-]
- Java的String
- 从尾到头打印链表
- php单例模式
- 集成第三方JavaScript库