HDU

先上题目:

Number Sequence

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


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
 
  题意就是给你两个数字序列,问你第二个序列在第一个序列的哪个位置第一次出现,如果没有出现过就输出-1。
  这题其实就是一个kmp,字符改成了数字,而且要注意的是模式串有可能比原串长,这时候就直接输出-1。
 
上代码:
 1 #include <stdio.h>
 2 #include <string.h>
 3 #define MAX 1000010
 4 using namespace std;
 5 
 6 int s[MAX],t[MAX],next[MAX],n,m;
 7 
 8 void get_next()
 9 {
10     int i,k;
11     memset(next,-1,sizeof(next));
12     i=0;
13     k=-1;
14     while(i<m)
15     {
16         if(k==-1 || t[i]==t[k]){i++;k++;next[i]=k;}
17         else k=next[k];
18     }/*
19     for(i=0;i<m;i++) printf("%d ",next[i]);
20     printf("
");
21     */
22 }
23 
24 int kmp()
25 {
26     int i,j;
27     i=0;j=0;
28     while(i<n && j<m)
29     {
30         if(j==-1 || s[i]==t[j]){i++; j++;}
31         else j=next[j];
32     }
33     if(j>=m) return i-m+1;
34     else return -1;
35 }
36 
37 int main()
38 {
39     int T,i;
40     //freopen("data.txt","r",stdin);
41     scanf("%d",&T);
42     while(T--)
43     {
44         scanf("%d %d",&n,&m);
45         for(i=0;i<n;i++) scanf("%d",&s[i]);
46         for(i=0;i<m;i++) scanf("%d",&t[i]);
47         if(m>n) printf("-1
");
48         else
49         {
50             get_next();
51             int f=kmp();
52             printf("%d
",f);
53         }
54     }
55     return 0;
56 }
1711(没有优化版)
原文地址:https://www.cnblogs.com/sineatos/p/3276410.html