HDU 1711 Number Sequence KMP
Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 42790 Accepted Submission(s): 17672
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
终于理解KMP了,开心
顺手敲了模板题
https://blog.csdn.net/v_JULY_v/article/details/7041827#t17
KMP详解超好
#include<bits/stdc++.h>
using namespace std;
int txt[1000005];
int net[10005];
int mode[10005];
void GetNext(int p[],int net[],int pLen)
{
//int pLen = strlen(p);
net[0]=-1;
net[1]=0;
int len=0;
for(int i=2; i<pLen; i++)
{
if(p[i-1]==p[len])
{
net[i]=net[i-1]+1;
len++;
}
else
{
net[i]=0;
len=0;
}
}
}
int KMP(int text[],int mode[],int net[],int len1,int len2)
{
// int len1=strlen(text);
// int len2=strlen(mode);
int i=0,j=0;
int l=0;
while(i<len1&&j<len2)
{
if(text[i]==mode[j]||j==-1)
{
i++;
j++;
}
else
{
j=net[j];
}
}
if(j==len2)
{
return i-len2+1;
}
else
return -1;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int lena,lenb;
scanf("%d%d",&lena,&lenb);
for(int i=0; i<lena; i++)
{
scanf("%d",&txt[i]);
}
for(int i=0; i<lenb; i++)
{
scanf("%d",&mode[i]);
}
GetNext(mode,net,lenb);
printf("%d\n",KMP(txt,mode,net,lena,lenb));
}
// next[0]=0;
// int net[1005];
return 0;
}
/*
13
13 5
1 1 3 4 5 6 1 1 3 4 5 6 5
3 4 5 6 5
*/