hash+栈做法相关疑问
查看原帖
hash+栈做法相关疑问
820948
qbhswmy楼主2023/11/14 15:26

AC:

#include <bits/stdc++.h>
#define ull unsigned long long
using namespace std;
int n;
map <ull,int> h;
ull p[2000005]={0},tmph,ans=0;
char s[2000005];
int stk[2000005]={0},top=0;
int main(){
//	freopen("game2.in","r",stdin);
	cin>>n;
	getchar();
	int tmp;
	p[0]=1;
	for(int i=1;i<=n;i++)
		p[i]=p[i-1]*131;
	tmph=0;
	h[0]=1;
	for(int i=1;i<=n;i++){
		s[i]=getchar();
		tmp=s[i]-'a'+1;
		if(top&&stk[top]==tmp){
			tmph-=p[top]*stk[top];
			top--;
		}
		else {
			stk[++top]=tmp;
			tmph+=p[top]*tmp;
		}
		ans+=h[tmph];
		h[tmph]++;
	}
	printf("%lld\n",ans);
	return 0;
}

25pts

#include <bits/stdc++.h>
#define ull unsigned long long
using namespace std;
int n;
map <ull,int> h;
ull p=131,tmph,ans=0;
char s[2000005];
int stk[2000005]={0},top=0;
int main(){
	cin>>n;
	getchar();
	int tmp;
	tmph=0;
	h[0]=1;
	for(int i=1;i<=n;i++){
		s[i]=getchar();
		tmp=s[i]-'a'+1;
		if(stk[top]==tmp){
			tmph=(tmph-stk[top])/p;
			top--;
		}
		else {
			stk[++top]=tmp;
			tmph=tmph*p+tmp;
		}
		ans+=h[tmph];
		h[tmph]++;
	}
	printf("%lld\n",ans);
	return 0;
}

rt,自己写出来的代码和题解的不太一样,就是hash部分的处理不一样,MnZn想知道为什么第二种会有问题,是溢出导致的吗

2023/11/14 15:26
加载中...