首页 > 代码库 > SDJZU_新生_字符串匹配(KMP)_A - Number Sequence

SDJZU_新生_字符串匹配(KMP)_A - Number Sequence

A - Number Sequence
Crawling in process...Crawling failedTime Limit:5000MS    Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
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
         
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int next[10007];
int x[1000077];
int y[1000077];
int main()
{
    int n;
    scanf("%d",&n);
    while(n--)
    {
        int a,b,i;
        scanf("%d%d",&a,&b);
        for(i=0;i<a;i++)
        {
            scanf("%d",&x[i]);
        }
        for(i=0;i<b;i++)
        {
            scanf("%d",&y[i]);
        }
        next[0]=next[1]=0;
        for(i=1;i<b;i++)
        {
            int j=next[i];
            while(j&&y[i]!=y[j])
            {
                j=next[j];
            }
            next[i+1]=y[i]==y[j]?j+1:0;
        }
        int j=0,flag=0;
        for(i=0;i<a;i++){
	    	while(j&&x[i] !=  y[j])j = next[j];
	    	if(x[i] == y[j])j++;
	    	if(j == b){flag = 1;break;}
	    }
	    if(flag)printf("%d\n",i-b+2);
	    else printf("-1\n");
    }
}

/*对于next那一块  ,直到现在感觉也不是很明白,这应该是核心了吧,只是照着我春哥的末班就写上了,现在仅仅是明白了KMP方法的思想了,却写不出来,只能通过做题慢慢磕了*/

/*后面这些代码是我春哥的,希望有助于以后的理解。*/
#include<stdio.h>
#include<string.h>
using namespace std;

int next[10010];
int aa[1000010];
void getNext(int *bb,int b){
	next [0] = next[1] = 0;
	for(int i=1;i<b;i++){
		int j = next[i];
		while(j&&bb[i]!=bb[j])j = next[j];
		next[i+1] =  bb[i] == bb[j]?j+1:0;
	}
}
int main(){
	int n,a,b,bb[10010];
    scanf("%d",&n);
    while(n--){
    	int flag = 0;
    	scanf("%d%d",&a,&b);
    	for(int i=0;i<a;i++){
	    	scanf("%d",&aa[i]);
	    }
	    for(int i=0;i<b;i++){
    		scanf("%d",&bb[i]);
    	}
    	getNext(bb,b);
    	int  j =0;
    	int i;
    	for(i=0;i<a;i++){
	    	while(j&&aa[i] !=  bb[j])j = next[j];
	    	if(aa[i] == bb[j])j++;
	    	if(j == b){flag = 1;break;}
	    }
	    if(flag)printf("%d\n",i-b+2);
	    else printf("-1\n");
    }
}


SDJZU_新生_字符串匹配(KMP)_A - Number Sequence