Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 50957 Accepted Submission(s): 20470
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,便了一点花样就是将字符串变成了中间用空格分开的数字。第一行:输入test数量,接下来第一行分别是text串的长度 N 和p串的长度 M ,接下来两行分别是text串和p串。
这个题在KMP模板上进行的改变是:
①:将字符串数组变为in型数组;
②:输入方式有变化,这里我又区分了一下 scanf 和 gets 的异同。
1.不同点:
scanf不能接受空格、制表符Tab、回车等;
而gets能够接受空格、制表符Tab和回车等;
2.相同点:
字符串接受结束后自动加’\0’。
所以我们在已知两串长度的情况下,用scanf输入。
注意:当匹配成功时输出的是第i个,而不是下标,所以要输出kmp函数返回的num值 + 1,当匹配失败时输出- 1;还有一个坑点 (仅仅相对于我,细心的朋友们自动略过) 是数据范围,数组要开足够大。
AC代码如下:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;
const int MAXN = 1000005;
int t[MAXN];
int p[10005];
int nxt[10005];
int N, M;
//建立公共前后缀表, /*****next[j] = k 代表p[j] 之前的模式串子串中,有长度为k 的相同前缀和后缀*****/
void GetNext(int p[], int nxt[]){ //
int i, j;
nxt[0] = 0;
for(j = 1, i = 0; j < M; j++){ //前缀 i,从0开始 后缀j,从1开始
while(i > 0 && p[j] != p[i])
i = nxt[i-1];
if(p[j] == p[i]){ //前后匹配时,next就加一
i++;
}
nxt[j] = i; //①p[j] != p[i] && i == 0,赋值0
//②p[j] == p[i] && i == 0,i已经加一(i在原匹配串上增加)
} //③p[j] == p[i] && i != 0,回溯过后,给值为第一次匹配的后一位
}
int kmp(int t[], int p[], int nxt[]){
int i, q;
GetNext(p, nxt);
for(i = 0, q = 0; i < N; i++){ // i时text串下标, q时p串下标
while(q > 0 && p[q] != t[i])
q = nxt[q-1]; // q-1前边的时公共前后缀,已经无需再比较,和p[nxt[q-1]]比较就行了
if(p[q] == t[i]){
if(p[q] == t[i]){ // 匹配不断后移q和i(i在for循环中已经移动)
q++;
}
if(q == M)
return i - M + 1; // i为最后位置,m为长度,那起始位置就是 i-m+1
}
}
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", &t[i]);
for(int i = 0; i < M; i++)
scanf("%d", &p[i]);
int num = kmp(t, p, nxt);
// printf("%s", t);
if(num != -1)
printf("%d\n",num + 1);
else
printf("%d\n", num);
}
return 0;
}