Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 31779 Accepted Submission(s): 13350
题目链接:点击打开链接
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
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
题意:
给你两个数组 a[1], a[2], ...... , a[N], 和b[1], b[2], ...... , b[M] ,N>M,让你找到一个K,使得 a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M].说白了,,就是让你找到第二个串在第一个串有没有与之匹配的,若有,则返回 a 数组中匹配的初始位置,否则输出-1.
分析:
KMP算法,今天花了两个小时自己模拟了一遍,终于完全明白了,等整理好今天下午写的几题之后,就来写写KMP的详解,一个模板,稍加修改,写了四个题。(这里分享一个要注意的地方,就是如果你用的数组名字叫next的话,就不要出现c++的头文件,提交会错,因为和c++里的东西重名了)
#include<stdio.h>
#include<string>
#include<string.h>
const int INF1=10005;
const int INF2=1000005;
int a[INF2],b[INF1];
int next[INF1];
int m,n;
void get_next()/// 求出模式串的next数组
{
next[0] = -1;
int k = -1;
for (int i = 1; i < m; i++)
{
while (k > -1 && b[k + 1] != b[i])
{
k = next[k];
}
if (b[k + 1] == b[i])
{
k = k + 1;
}
next[i] = k;
}
}
int KMP()
{
get_next();
int k = -1;
for (int i = 0; i < n; i++)
{
while (k >-1&& b[k + 1] != a[i])
{
k = next[k];
}
if (b[k + 1] == a[i])
k = k + 1;
if (k == m-1)
{
return (i-m+2);///因为我的下标是从0开始的,所以应该加2
}
}
return -1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
for(int i=0;i<m;i++)
scanf("%d",&b[i]);
int k=KMP();
printf("%d\n",k);
}
return 0;
}