Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 22520 Accepted Submission(s): 9623
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
Source
Recommend
题目大意:
给出两个串,a,b。问a中是否有串 b ,如果有,输出串 b 的首字符的位置。不然输出 -1
思路:
裸 KMP 。
AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int str1[1000005], str2[10005];
int nextval[10005];
int lens, lenp;
void getnext(const int *p, int nextval[]) //前缀函数(滑步函数)
{
int i = 0, j = -1;
nextval[0] = -1;
while(i != lenp)
{
if(j == -1 || p[i] == p[j]) //(全部不相等从新匹配 || 相等继续下次匹配)
{
++i, ++j;
if(p[i] != p[j]) //abcdabce
nextval[i] = j;
else //abcabca
nextval[i] = nextval[j];
}
else
j = nextval[j]; //子串移动到第nextval[j]个字符和主串相应字符比较
}
}
int KMP(int*s, int*p, int nextval[]) //KMP算法
{
int i = 0, j = 0; //s和j字符串从头开始比较
while(i != lens && j != lenp)
{
if(s[i] == p[j]) //相等继续匹配
++i, ++j;
else
{
if(nextval[j] == -1) //-1代表与p[0]间接比较过,需要主串后移,p重新从头匹配
++i, j = 0;
else
j = nextval[j]; //直接右移nextval[j]位与s[i]比较
}
}
if(j == lenp) //返回从主串第几个元素开始匹配
return i - j;
else
return -1;
}
int main() //主串子串位置从0开始
{
int pos;
int T;
scanf("%d",&T);
while(T--) //str1为主串,str2为子串
{
scanf("%d%d",&lens,&lenp);
int x;
for(int i=0;i<lens;i++)
{
scanf("%d",&str1[i]);
}
for(int i=0;i<lenp;i++)
{
scanf("%d",&str2[i]);
}
getnext(str2, nextval); //求子串的前缀函数
pos = KMP(str1, str2, nextval);
if(pos==-1)
printf("%d\n", pos);
else
printf("%d\n", pos+1);
}
return 0;
}