http://acm.hdu.edu.cn/showproblem.php?pid=1711
Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 30591 Accepted Submission(s): 12870
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.
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].
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
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
Source
把数字离散化后当作字符来处理就是kmp了,注意模板是从下标0开始的我一直输入时从1开始导至答案不对。
#include<cstring>
#include<cstdio>
#include<map>
#include<iostream>
using namespace std;
map<int,int>M;
int nex[],l1,l2,sl;
int S[],T[];
int solve()
{
int i,j;
nex[]=nex[]=;
for(i=;i<l2;++i)
{
j=nex[i];
while(j&&T[i]!=T[j])j=nex[j];
nex[i+]=T[i]==T[j]?j+:;
}
j=;
for(i=;i<l1;++i)
{
while(j&&S[i]!=T[j])j=nex[j];
if(S[i]==T[j]){
j++;
if(j==l2)return i-l2+;
}
}
return -;
}
int main()
{
int i,j,t,p,x,tmp;
cin>>t;
while(t--){p=;M.clear();
scanf("%d%d",&l1,&l2);
for(i=;i<l1;++i)
{
scanf("%d",&x);
tmp=M[x];
if(!tmp){M[x]=S[i]=++p;}
else S[i]=tmp;
}
for(i=;i<l2;++i)
{
scanf("%d",&x);
tmp=M[x];
if(!tmp){M[x]=T[i]=++p;}
else T[i]=tmp;
}
cout<<solve()<<endl;;
}
return ;
}