hdoj 1711 Number Sequence【kmp(数字数组)】

来源:互联网 发布:怎么在淘宝网开网店 编辑:程序博客网 时间:2024/06/08 11:08

Number Sequence

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15877    Accepted Submission(s): 7000


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
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
 

Source
HDU 2007-Spring Programming Contest
 
思路:
       这一道题是将以前的字符数组变成数字数组进行比较计算,然后将找到的末尾下标减去子串的长度再加1,就是所求的下标值!
       注意:下标从1开始!所以才加1!
 
代码:
<span style="color:#000000;">#include <stdio.h>#include <string.h>int a[10005];int b[1000005];int p[10005];int lena,lenb;void getp(){int i=0,j=-1;p[0]=-1;while(i<lena){if(j==-1||a[i]==a[j]){i++;j++;p[i]=j;}elsej=p[j];}}void kmp(){getp();int i=0,j=0;while(i<lenb){if(j==-1||b[i]==a[j]){i++;j++;if(j==lena){printf("%d\n",i-lena+1);return;}}elsej=p[j];}printf("-1\n");}int main(){int T;scanf("%d",&T);while(T--){scanf("%d%d",&lenb,&lena);for(int i=0;i<lenb;i++){scanf("%d",&b[i]);}for(int i=0;i<lena;i++){scanf("%d",&a[i]);}kmp();}return 0;}</span>

0 0
原创粉丝点击