码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1711 最基础的kmp算法

时间:2014-07-23 12:27:06      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   os   io   

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 }

 

HDU1711 最基础的kmp算法,布布扣,bubuko.com

HDU1711 最基础的kmp算法

标签:des   style   blog   color   os   io   

原文地址:http://www.cnblogs.com/CSU3901130321/p/3862213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!