社区讨论

不懂就问

P3375【模板】KMP参与者 7已保存回复 13

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
13 条
当前快照
1 份
快照标识符
@miec2pbo
此快照首次捕获于
2025/11/25 16:48
3 个月前
此快照最后确认于
2025/11/25 17:59
3 个月前
查看原帖
//https://www.luogu.com.cn/record/249497739 https://www.luogu.com.cn/record/249498288 为什么把kmp数组改成next数组在评测机上会报错 在本地却没问题 是因为next是关键字吗 求dalao解答 快考NOIP了,有点担心这个点 附代码
CPP
//可通过
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
string s1,s2;
int kmp[N];
int main(){
	cin>>s1>>s2;
	int r1=0;//s2前缀末尾 
	int len1=s1.length(),len2=s2.length();
	for(int r2=1;r2<len2;r2++){;//s2后缀末尾 
		while(r1>0&&s2[r1]!=s2[r2])	r1=kmp[r1-1];
		if(s2[r1]==s2[r2])	r1++;//最多前进一次 
		kmp[r2]=r1;
	}
	int l2=0;
	for(int l1=0;l1<=len1;l1++){
		while(l2>0&&s1[l1]!=s2[l2])	l2=kmp[l2-1];
		if(s1[l1]==s2[l2]){
		//	printf("(%d)",l2);
			l2++;
			if(l2==len2){
				printf("%d\n",l1-len2+2);
				l2=kmp[l2-1];
			}
			
			
		}
		//else l2=kmp[l2-1];
	} 
	for(int i=0;i<len2;i++)	printf("%d ",kmp[i]);
}
CPP
//不可通过
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
string s1,s2;
int next[N];
int main(){
	cin>>s1>>s2;
	int r1=0;//s2前缀末尾 
	int len1=s1.length(),len2=s2.length();
	for(int r2=1;r2<len2;r2++){;//s2后缀末尾 
		while(r1>0&&s2[r1]!=s2[r2])	r1=next[r1-1];
		if(s2[r1]==s2[r2])	r1++;//最多前进一次 
		next[r2]=r1;
	}
	int l2=0;
	for(int l1=0;l1<=len1;l1++){
		while(l2>0&&s1[l1]!=s2[l2])	l2=next[l2-1];
		if(s1[l1]==s2[l2]){
		//	printf("(%d)",l2);
			l2++;
			if(l2==len2){
				printf("%d\n",l1-len2+2);
				l2=next[l2-1];
			}
			
			
		}
		//else l2=kmp[l2-1];
	} 
	for(int i=0;i<len2;i++)	printf("%d ",next[i]);
}

回复

13 条回复,欢迎继续交流。

正在加载回复...