hdu 1711 Number Sequence

来源:互联网 发布:windowsce软件 编辑:程序博客网 时间:2024/05/22 09:06

Number Sequence
Time Limit: 5000MS Memory Limit: 32768KB 64bit IO Format: %I64d & %I64u

[Submit]   [Go Back]   [Status]  

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

213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
 

Sample Output

6-1
 

裸的KMP,输入时处理一下

#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>#include <stack>#include <cmath>#include <queue>#include <map>using namespace std;#define N 2001000int s[N];int pattern[N];int nest[N];int n,m;void getnext(){    //int len=strlen(pattern);    int j=-1;    nest[0]=-1;    for(int i=1;i<m;i++) {        while(j!=-1&&pattern[i]!=pattern[j+1])            j=nest[j];        if(pattern[j+1]==pattern[i])            j++;        nest[i]=j;    }}int main(){    int T;    scanf("%d",&T);    //getchar();    while(T--) {        char ch;        scanf("%d%d",&n,&m);        //getchar();        int i=0;        for(int i=0;i<n;i++)            scanf("%d",&s[i]);        for(int i=0;i<m;i++)            scanf("%d",&pattern[i]);        if(m>n) {            printf("-1");            continue;        }        getnext();        //int len1=strlen(s),len2=strlen(pattern);        int j=-1;      //  cout<<s<<endl<<pattern<<endl;        for(i=0;i<n;i++) {            while(j!=-1&&s[i]!=pattern[j+1])                j=nest[j];            if(s[i]==pattern[j+1])                j++;            if(j==m-1)                break;        }        if(j!=m-1)            printf("-1\n");        else            printf("%d\n",i-j+1);    }    return 0;}




原创粉丝点击