Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 29660 Accepted Submission(s): 12477
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
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711
题意:输入两个数组A[]和B[]的长度n,m和数组A,B,问数组B在数组A中首次出现的次数,即使得A[k]=B[0],A[k+1]=B[1]...A[k+m-1]=B[m-1]的最小k,不存在的话就输出-1。
解题思路:其实就是字符串匹配的问题,裸的KMP,所以直接套用KMP算法就好啦。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 1e6 + 10;
const int MAXM = 1e4 + 10;
int A[MAXN];//母串
int B[MAXM];//子串
int fail[MAXM];//失配数组
int N,M;//数组长度
void getFail()//得到失配函数
{
fail[0]=0;
fail[1]=0;
for(int i=1;i<M;i++)
{
int j=fail[i];
while(j && B[i]!=B[j]) j=fail[j];
fail[i+1]=B[i]==B[j]?j+1:0;
}
}
int find()//查询函数
{
memset(fail,0,sizeof(fail));
getFail();//得到失配数组
int j=0;
for(int i=0;i<N;i++)//匹配
{
while(j && B[j]!=A[i]) j=fail[j];
if(A[i]==B[j]) j++;
if(j==M) return i+2-M;//找到匹配的地方直接返回
}
return -1;//不存在,返回-1
}
int main(void)
{
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]);
}
printf("%d\n",find());
}
return 0;
}
本文介绍了一种使用KMP算法解决特定序列匹配问题的方法。该问题要求在大规模序列A中查找小规模序列B首次完全出现的位置。通过实现KMP算法,可以高效地解决这一挑战。
542

被折叠的 条评论
为什么被折叠?



