kmp算法

#include<bits/stdc++.h>
using namespace std;

const int N = 1e4 + 10;
int a[1000000],b[N];
int nex[N];
void GetNext(int *x,int len)
{
	//int len = s.lengt();
	nex[0] = -1;
	for(int i = 1,j = -1;i < len;i++)
	{
		while(j >= 0 && x[i] != x[j+1]) j = nex[j];
		if(x[i] == x[j+1]) ++j;
		nex[i] = j;
	}
}

int kmp(int *x,int *y,int l1,int l2)
{
	//int l1 = s1.length(),l2 = s2.length();
	int pos =  -1;
	for(int i = 0,j = -1; i < l1;i++)
	{
		while(j >= 0 && (j == l2 - 1 || x[i] != y[j+1]))
		j = nex[j];
		if(x[i] == y[j+1])
		++j;
		if(j == l2 - 1)
		{
			pos = i - l2 + 2;
			break;
		}
	}
	return pos;
}

int main()
{
	int t,n,m;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		for(int i = 0;i < n;i++)
		scanf("%d",&a[i]);
		
		for(int j = 0;j < m;j++)
		scanf("%d",&b[j]);
		
		GetNext(b,m);
		int ans = kmp(a,b,n,m);
		printf("%d
",ans);
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/mch5201314/p/11962625.html