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 DescriptionGiven 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.
InputThe 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].
OutputFor each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
Sample Input213 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 Output6-1
SourceHDU 2007-Spring Programming Contest
Recommendlcy
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
6-1
这个题目是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;
}
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- hdu1711
- kmp hdu1711
- hdu1711 kmp
- hdu1711(kmp)
- HDU1711-KMP
- 第九天(函数进阶 · 二)
- FW - Semi-Aggregate Property (need to H)
- android GPS LocationListener类
- Ubuntu文件系统和目录结构
- 网宿校招笔试题节选
- hdu1711
- DirectShow开发自己的Filter
- 解决Tomcat乱码
- iOS-正则表达式匹配数字或网址
- joj1995
- ajax详细解说(含jsp的高级特性)
- C#中基类和派生类的构造函数以及变量的执行顺序整理
- DirectShow 枚举设备
- Mac 在vmware中更改分辨率