KMP入门(匹配)
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
解题思路:题目大意:判断第一个串中是否存在第二个串,存在则输出最小的匹配起始位置,不存在则输出-1。
利用fail数组,KMP.
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int N[1000005],M[10005],fail[10005]; int n,m; void KMP(); int main() { int T; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&N[i]); for(int i=1;i<=m;i++) scanf("%d",&M[i]); KMP(); } return 0; } void KMP() { memset(fail,0,sizeof(fail)); fail[0]=-1;//初始化fail数组 for(int i=1;i<=m;i++) { int p=fail[i-1]; //如果不满足要求则一直fail直到p=0 while(p>=0&&M[p+1]!=M[i]) p=fail[p]; fail[i]=p+1; } int ans=0; for(int i=1,p=0;i<=n;i++) { while(p>=0&&M[p+1]!=N[i]) p=fail[p]; if(++p==m) { ans=i-m+1; p=fail[p]; break; } } if(ans) printf("%d\n",ans); else printf("-1\n"); }

浙公网安备 33010602011771号