首页 > 代码库 > HDU1711 最基础的kmp算法

HDU1711 最基础的kmp算法

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.
 
 
这是一道对kmp算法的最基础运用,在这里主要注意kmp函数以及得到next的函数的写法
 
代码如下:
 1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4  5 int n,m; 6 int a[1000010],b[10010],next[10010]; 7  8 void getnext (int *s,int *next){ 9     next[0]=next[1]=0;10     for (int i=1;i<m;i++){11         int j=next[i];12         while (j&&s[i]!=s[j])13             j=next[j];14         if(b[i]==b[j]) next[i+1]=j+1;15         else next[i+1]=0;16     }17 }18 19 int kmp (int *a,int *b,int *next){20     getnext (b,next);21     int j=0;22     for (int i=0;i<n;i++){23         while (j&&a[i]!=b[j])24             j=next[j];25         if (a[i]==b[j])26             j++;27         if (j==m)28             return i-m+2;29     }30     return -1;31 }32 33 int main (){34     int t;35     scanf ("%d",&t);36     while (t--){37         scanf ("%d %d",&n,&m);38         for (int i=0;i<n;i++)39             scanf ("%d",&a[i]);40         for (int i=0;i<m;i++)41             scanf ("%d",&b[i]);42         int ans=kmp (a,b,next);43         printf ("%d\n",ans);44     }45     return 0;46 }