扩展KMP模板

扩展KMP在这里我就不说明了,详见刘雅琼的讲义:
http://wenku.baidu.com/view/8e9ebefb0242a8956bece4b3.html
Code:

void get_nt(char *s, int n, int *nt) {
	int p = 2, mx = 1;
	while(mx < n && s[mx] == s[mx + 1]) mx ++;
	nt[1] = n; nt[2] = mx - 1;
	fo(i, 3, n) {
		if(nt[i - p + 1] >= mx - i + 1) {
			int j = max(0, mx - i + 1);
			while(i + j <= n && s[j + 1] == s[i + j]) j ++;
			nt[i] = j; p = i; mx = i + j - 1;
		} else nt[i] = nt[i - p + 1];
	}
}
void solve(char *s, char *t, int *nt, int n, int m, int *l) {
	int p = 1, mx = 0;
	while(mx < min(n, m) && s[mx + 1] == t[mx + 1]) mx ++;
	l[1] = mx;
	fo(i, 2, m) {
		if(nt[i - p + 1] >= mx - i + 1) {
			int j = max(0, mx - i + 1);
			while(j + 1 <= n && i + j <= m && s[j + 1] == t[i + j]) j ++;
			l[i] = j; p = i; mx = i + j - 1;
		} else l[i] = nt[i - p + 1];
	}
}

你可能感兴趣的:(模版,ExKmp)