标签:
http://acm.hdu.edu.cn/showproblem.php?pid=1711
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16080 Accepted Submission(s): 7100
Next里面存的是前缀和后缀的最大相似度
Next[i] 代表的是前 i 个数的最大匹配
#include<stdio.h> #include<string.h> #include<stdlib.h> #define N 1000007 int M[N], S[N], Next[N]; void FindNext(int Slen) { int i=0, j=-1; Next[0] = -1; while(i<Slen) { if(j==-1 || S[i]==S[j]) Next[++i] = ++j; else j = Next[j]; } } int KMP(int Mlen, int Slen) { int i=0, j=0; FindNext(Slen); while(i<Mlen) { while(j==-1 || (M[i]==S[j] && i<Mlen && j<Slen)) i++, j++; if(j==Slen) return i-Slen+1; j = Next[j]; } return -1; } int main() { int t; scanf("%d", &t); while(t--) { int n, m, i; scanf("%d%d", &n, &m); for(i=0; i<n; i++) scanf("%d", &M[i]); for(i=0; i<m; i++) scanf("%d", &S[i]); printf("%d\n", KMP(n, m)); } return 0; }
(模板题)Number Sequence -- Hdu -- 1711
标签:
原文地址:http://www.cnblogs.com/YY56/p/4833430.html