求调(哈希)
查看原帖
求调(哈希)
1471248
lifeam楼主2024/10/14 21:16
#include<bits/stdc++.h> 
using namespace std;
int n,sum;
string a;
int h[2000001];
map<int,int>ma;
set<int>s;
stack<char>q;
stack<int>p;
int main(){
	cin>>n;
	cin>>a;
	a='$'+a;		
	s.insert(0);
	ma[0]++;
	for (int j=1;j<=n;j++){
		if (!q.empty()&&q.top()==a[j]){
			h[j]=h[p.top()];
			ma[h[j]]++;
			
			q.pop();
			p.pop();
		//	cout<<j<<' '<<c<<endl;
		}
		else{
			q.push(a[j]);
			p.push(j-1);
			h[j]=h[j-1]*33+a[j]-'a'+1;
			s.insert(h[j]);
			ma[h[j]]++;
		}
	}
	for (int i:s){
		sum+=ma[i]*(ma[i]-1)/2;
	}
	cout<<sum<<endl;
	return 0;
} 
2024/10/14 21:16
加载中...