HDOJ1711(Number Sequence)

Number Sequence

Time Limit: 1000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 768    Accepted Submission(s): 278


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

 

 

/*
    2009-05-10 11:04:54 Accepted 1711 515MS 4192K 944 B C++ 
    试着把自己做的模板用一下 
*/
 
#include 
<iostream>
#include 
<cstdio>
using namespace std;

const int M = 10004;
const int N = 1000004;

int S[N],//主串    
    T[M];//模式串
int Slen, Tlen;//主串和模式串的长度
int next[M];

void get_next()
{
    
int j, k;

    j 
= 0; k = -1; next[0= -1;

    
while(j < Tlen)
        
if(k == -1 || T[j] == T[k])
        
{
            next[
++j] = ++k;
        }

        
else
            k 
= next[k];

}


int KMP_Index()
{//此函数用于返回模式串在主串中第一次出现的位置
 
//不存在返回-1
    int i, j;
    i 
= j = 0;

    get_next();

    
while(i < Slen && j < Tlen)
        
if(j == -1 || S[i] == T[j])
        
{
            i
++; j++;
        }

        
else
            j 
= next[j];

    
if(j == Tlen)
        
return i - Tlen;
    
else
        
return -2;

}


int main()
{
    
int n, i;
    scanf(
"%d"&n);
    
while(n--)
    
{
        scanf(
"%d%d"&Slen, &Tlen);
        
for(i = 0; i < Slen; i++)
            scanf(
"%d", S + i);
        
for(i = 0; i < Tlen; i++)
            scanf(
"%d", T + i);
            
        printf(
"%d\n", KMP_Index() + 1);
    }

    
return 0;
}

posted on 2009-05-10 11:08  Xredman  阅读(220)  评论(0编辑  收藏  举报

导航