为何二分+哈希=TLE
查看原帖
为何二分+哈希=TLE
239832
sipu6174楼主2020/7/14 15:23
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
char s[300010];
ull hs1[300010],hs2[300010];
ull pow17[300010],pow19[300010];
ull gethsh1(int l,int r){return hs1[r]-hs1[l-1]*pow17[r-l+1];}
ull gethsh2(int l,int r){return hs2[r]-hs2[l-1]*pow19[r-l+1];}
pair<ull,ull> p;
map<pair<ull,ull>,bool>used;
int n;
bool check(int len){
	used.clear();
	for(int i=1;i<=n;i++){
		int l=i,r=i+len-1;
		if(r>n) break;
		ull res1=hs1[r]-hs1[l-1]*pow17[r-l+1];
		ull res2=hs2[r]-hs2[l-1]*pow19[r-l+1];
		p.first=res1,p.second=res2;
		if(!used[p]) used[p]=1;
		else return 1;
	}
	return 0;
}
int main(){
	pow17[0]=pow19[0]=1;
   for(int i=1;i<=300000;i++) 
      pow17[i]=pow17[i-1]*17,pow19[i]=pow19[i-1]*19;
	cin>>n>>s+1;
	for(int i=1;i<=n;i++) {
		hs1[i]=(hs1[i-1]*17+s[i]);
		hs2[i]=(hs2[i-1]*19+s[i]);		
	}
	int l=0,r=n;
	while(l+1<r){
		int mid=l+r>>1;
		if(check(mid)) l=mid;
		else r=mid;
	}
	cout<<l;
	return 0;
}
2020/7/14 15:23
加载中...