hdu 1711 kuangbin 字符串 A KMP入门

来源:互联网 发布:汤神君没有朋友知乎 编辑:程序博客网 时间:2024/06/05 11:19

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入门。
注意此题数据很多。应用Scanf,cin会超时。
但是用scanf就不能定义为字符数组,这个需要注意。

代码:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn = 1000000+100;const int maxm = 10000+100;int nt[maxn];int S[maxn],T[maxm];int slen,tlen;void getNext(){   int j,k;   j=0;k=-1;nt[0]=-1;   while(j<tlen)   {       if(k==-1||T[j]==T[k])       {           nt[++j] = ++k;       }       else       {           k=nt[k];       }   }   return ;}int indexKMP(){    int i=0;    int j=0;    getNext();    while(i<slen&&j<tlen)    {        if(j==-1||S[i]==T[j])        {            i++;            j++;        }        else        {            j=nt[j];        }    }    if(j==tlen)    {        return i-tlen;    }    else    {        return -1;    }}int main(){    int ks;    cin>>ks;    while(ks--)    {        int n,m;        scanf("%d%d",&n,&m);        for(int i=0;i<n;i++)        {           scanf("%d",&S[i]);        }        for(int i=0;i<m;i++)        {            scanf("%d",&T[i]);        }        slen = n;        tlen = m;       int ans = indexKMP();       if(ans==-1)       {           cout<<-1<<endl;       }       else       {           cout<<ans+1<<endl;       }    }    return 0;}
原创粉丝点击