next数组有问题求调
查看原帖
next数组有问题求调
1179906
hhy8399楼主2025/1/5 23:17
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e6 + 10;

int next[MAXN],next_val[MAXN];
string c,t;

void GetNext(string s) {
	::next[0] = -1;
	int slen = s.size();
	if(slen == 1) {
		return ;
	}
	::next[1] = 0;
	if(slen == 2) {
		return ;
	}
	for(int i = 2;i < slen;i++) {
		int newc = s[i - 1];
		if(newc == s[::next[i - 1]]) {
			::next[i] = ::next[i - 1] + 1;
		}
		else {
			int cur = ::next[i - 1];
			while(s[cur] != newc) {
				if(cur == -1) {
					break;
				}
				cur = ::next[cur];
			}
			::next[i] = cur + 1;
		}
	}
}

void NextToNext_Val(string s) {
	int slen = s.size();
	next_val[0] = -1;
	if(slen == 1) {
		next_val[1] = 0;
		return ;
	}
	for(int i = 1;i < slen;i ++) {
		if(s[i] == s[::next[i]]) {
			next_val[i] = next_val[::next[i]];
		}
		else {
			next_val[i] = ::next[i];
		}
	}
}

int KMP(string s,string p) {
	int i = 0,j = 0;
	int slen = s.size(),plen = p.size();
	while(i < slen && j < plen) {
		if(s[i] == p[j]) {
			i ++;
			j ++;
		}
		else {
			j = ::next[j];
			if(j == -1) {
				j = 0;
				i ++;
			}
		}
	}
	if(j >= plen) {
		return i - plen;
	}
	return -1; 
}

int main() {
	ios::sync_with_stdio(0);cin.tie(0);
	cin >> c >> t;
	GetNext(t);
//	NextToNext_Val(t);
	while(true) {
		int k = KMP(c,t);
		if(k == -1) {
			break;
		}
		printf("%d\n",k + 1);
		c[k] = -1;
	}
	for(int i = 0;i < t.size();i ++) {
		printf("%d ",::next[i]);
	}
	return 0;
}
2025/1/5 23:17
加载中...