hdu 1711 Number Sequence (kmp)

hdu 1711 题目链接

题意:给定两个数列,问第二个数列在第一个数列中出现的位置(第一个元素对应的位置)

思路:数列也可以看成字符串,然后左kmp,返回的答案是i+1-m。。。1A

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年08月11日 星期四 02时30分23秒
 4File Name :code/hdu/1711.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <stack>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <deque>
19#include <ctime>
20#define fst first
21#define sec second
22#define lson l,m,rt<<1
23#define rson m+1,r,rt<<1|1
24#define ms(a,x) memset(a,x,sizeof(a))
25typedef long long LL;
26#define pi pair < int ,int >
27#define MP make_pair
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=1E6+7;
34const int M=1E4+7;
35int a[N];
36int b[M];
37int nxt[M];
38int n,m;
39void getnxt(int n)
40{
41    int i = 0;
42    int j = -1;
43    nxt[0] = -1;
44    while (i<n)
45	if (j==-1||b[i]==b[j]) nxt[++i]=++j;
46	else j = nxt[j];
47}
48int kmp( int n,int m)
49{
50    getnxt(m);
51    int i = 0;
52    int j = 0;
53    while (i<n)
54    {
55	if (j==-1||a[i]==b[j]) i++,j++;
56	else j = nxt[j];
57	if (j==m) return i+1-m;
58    }
59    return -1;
60}
61int main()
62{
63	#ifndef  ONLINE_JUDGE 
64	freopen("code/in.txt","r",stdin);
65  #endif
66	int T;
67	scanf("%d",&T);
68	while (T--)
69	{
70	    scanf("%d%d",&n,&m);
71	    for ( int i = 0 ; i < n ; i++) scanf("%d",&a[i]);
72	    for ( int i = 0 ; i < m ; i++) scanf("%d",&b[i]);
73	    int ans = kmp(n,m);
74	    printf("%d\n",ans);
75	}
76  #ifndef ONLINE_JUDGE  
77  fclose(stdin);
78  #endif
79    return 0;
80}