hdu1711

来源:互联网 发布:mac无法接收打包文件 编辑:程序博客网 时间:2024/06/07 06:21

Number Sequence

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


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
 

Recommend
lcy
 

这个题目是kmp问题,关键在于构造失败函数。
#include<stdio.h>
#include<iostream>
using namespace std;
int s[1000000+2];
int t[10000+2];
int f[10000+2];
int n,m;
void fail()
{
    f[0]=-1;
    for(int j=1;j<m;j++)
    {
        int i=f[j-1];
        while(t[j]!=t[i+1]&&i>=0)i=f[i];
        if(t[j]==t[i+1])f[j]=i+1;
        else f[j]=-1;
    }
}
int kmp()
{
    fail();
    int i,j;
    i=0;
    j=0;
    while(i<n&&j<m)
    {
        if(s[i]==t[j])
        {
            i++;j++;
        }
        else
        {
            if(j==0)
                i++;
            else
            {
                j=f[j-1]+1;
            }
        }
    }
    if(j<m)return -1;
    else return i-m+1;
}
int main()
{
    int d;
    cin>>d;
    for(int j=1;j<=d;j++)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;i<n;i++)
            cin>>s[i];
        for(int ii=0;ii<m;ii++)
            cin>>t[ii];
        cout<<kmp()<<endl;
    }
    return 0;
}

原创粉丝点击