萌新刚学哈希,代码WA求调
查看原帖
萌新刚学哈希,代码WA求调
732988
JacoAquamarine楼主2023/9/5 19:19

RT,过了样例,WA0pts

#include<bits/stdc++.h>
#define rep(a,b,c) for(int a=b;a<=c;a++)
#define ULL unsigned long long
const int Maxn=4e4+5;
const ULL x=123;
using namespace std;
int N,sa[Maxn];
ULL H[Maxn],PX[Maxn],Hash[Maxn];
void init_PX(){
	PX[0]=1;
	rep(i,1,Maxn)PX[i]=x*PX[i-1];
}
void init_hash(const string &s){
	N=s.length();
	H[N]=0;
	for(int i=N-1;i>=0;i--){
		H[i]=(s[i]-'a'+1)+H[i+1]*x;
	}
}
bool hash_cmp(int a,int b){
	if(Hash[a]!=Hash[b])return Hash[a]<Hash[b];
	return a<b;
}
bool ok(int L,int M,int & pos){
	rep(i,0,N-L+1){
		sa[i]=i;
		Hash[i]=H[i]-H[i+L]*PX[L];
	}
	sort(sa,sa+N-L+1,hash_cmp);
	pos=-1;int c=0;
	rep(i,0,N-L+1){
		if(i==0||Hash[sa[i]]!=Hash[sa[i-1]])c=0;
		if(++c>=M)pos=max(pos,sa[i]);
	}
	return pos>0;
}
int main(){
	init_PX();
	string word;
	for(int t=0,pos,M;cin>>M>>word&&M;t++){
		init_hash(word);
		if(!ok(1,M,pos)){
			puts("none");
			continue;
		}
		int l=1,r=N+1;
		while(l+1<r){
			int m=l+(r-l)/2;
			if(ok(m,M,pos))l=m;
			else r=m;
		}
		ok(l,M,pos);
		cout<<l<<" "<<pos<<endl;
	}
	return 0;
}
2023/9/5 19:19
加载中...