很简单的一道题。
D - Number Sequence
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
输入
输入的第一行是一个数字T,表示事例的数量。 每个案件包含三行。 第一行是两个数字N和M(1 <= M <= 10000,1 <= N <= 1000000)。 第二行包含N个表示[1],a [2],......,a [N]的整数。 第三行包含M个整数,表示b [1],b [2],......,b [M]。 所有整数都在[-1000000,1000000]的范围内。
产量
对于每个测试用例,应该输出一行只包含上述K的行。 如果不存在这样的K,则输出-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
示例输出
6
-1
感觉这是第二简单的题目,之前WA了一遍,因为(竟然)没发现数字之间有空格。其实有空格的隔开的输入很好想的,上学期学C语言的时候课后题就有关于这方面的问题,现在正好用得着。我记得scanf就是这样的。用scanf输入字符中间不需要有空格(或者说是不能有),而输入数字的时候两个数字之间必须有空格。
有的同学做这道题卡时间了,可能使用了cin,这个比scanf慢很多。
代码如下:
#include "cstdio"
#include "iostream"
#include "cstring"
using namespace std;
int N, M;
int s[1000001];///this is the main
int f[10001];///this is the one to be find
int ne[10001];///这个数组中盛放的是匹配字符串的next值
void GetNext(int *a)///这个函数是为了标记匹配字符串的next值
{
int i = 0, j = -1;
ne[0] = -1;
while(i < M)
{
if(j == -1 || a[i] == a[j])
{
ne[++i] = ++j;
}
else j = ne[j];
}
}
///实际上每求一个next值要循环两遍
int KMP(int *a, int *b)
{
int i = 0, j = 0;
while (i < N && j < M)
{
if(j == -1 || a[i] == b[j])
{
j++;
i++;
}
else
j = ne[j];
}
if(j == M)
return i-j+1;
else
return -1;
}
int main()
{
int n;
scanf("%d", &n);
while(n--)///使用这种方法比写for循环简便
{
scanf("%d%d", &N, &M);
for(int h = 0; h < N; h++)
scanf("%d", &s[h]);
for(int h = 0; h < M; h++)
scanf("%d", &f[h]);
GetNext(f);
cout << KMP(s,f) << endl;
}
return 0;
}
可见代码基本上没有改动,只是改了输入方式并把char全部换成了int。