Number Sequence kmp
阿新 • • 發佈:2019-04-08
exists sizeof rip cout code make nbsp c++ eof
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.
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.
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; }View Code
Number Sequence kmp