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 是一道模板题
不过还是wa了两发
1.不能开next数组 和系统自带名字重名
2.一开始我是把一个个数据转化成一条字符串来进行kmp 但是显然是错的QWQ
改成数组形式就行了
#include<bits/stdc++.h> using namespace std; //input #define rep(i,a,b) for(int i=(a);i<=(b);i++) #define repp(i,a,b) for(int i=(a);i>=(b);i--) #define RI(n) scanf("%d",&(n)) #define RII(n,m) scanf("%d%d",&n,&m); #define RIII(n,m,k) scanf("%d%d%d",&n,&m,&k) #define RS(s) scanf("%s",s); #define ll long long #define inf 0x3f3f3f3f #define REP(i,N) for(int i=0;i<(N);i++) #define CLR(A,v) memset(A,v,sizeof A) // int nex[100000+5]; int lenp,lens; int p[10000+5];//可以是char 也可以是string int s[1000000+5]; void getnext() { nex[0]=-1; int k=-1,j=0; while(j<lenp-1) { if(k==-1||p[j]==p[k]) nex[++j]=++k; else k=nex[k]; } } int kmp() { //lens= //lenp= int j=0; int i=0; while(i<lens&&j<lenp) { if(s[i]==p[j]||j==-1) { i++; j++; } else j=nex[j]; if(j==lenp) { return i-j+1; } } return -1; } int main() { int cas; RI(cas); while(cas--) { RII(lens,lenp); rep(i,0,lens-1) RI(s[i]); rep(i,0,lenp-1) RI(p[i]); getnext(); cout<<kmp()<<endl; } return 0; }