1. 程式人生 > >KMP演算法總結

KMP演算法總結

模板

#include<bits/stdc++.h>
#define REP(i, a, b) for(register int i = (a); i < (b); i++)
#define _for(i, a, b) for(register int i = (a); i <= (b); i++)
using namespace std;

const int MAXN = 1e6 + 10;
const int MAXM = 1e3 + 10;
char a[MAXN], b[MAXM]; 
int next[MAXM], lena, lenb; 

void get_next()
{
	next[1] = 0; int j = 0;
	_for(i, 2, lenb)
	{
		while(j > 0 && b[j + 1] != b[i]) j = next[j];
		if(b[j + 1] == b[i]) j++;
		next[i] = j;	
	} 
}

void kmp()
{
	int j = 0;
	_for(i, 1, lena)
	{
		while(j > 0 && (j == lenb || b[j + 1] != a[i]))  j = next[j]; 
		if(b[j + 1] == a[i]) j++;
		if(j == lenb) { printf("%d %d\n", i - lenb + 1, i); return; }	
	}
	puts("NO");
}

int main()
{
	scanf("%s%s", a + 1, b + 1);
	lena = strlen(a + 1); lenb = strlen(b + 1);
	get_next();
	kmp();
	return 0;
}