哈希做法,#11 #12 TLE 死循环,求住
#include <bits/stdc++.h>
#define int long long
#define ull unsigned long long
using namespace std;
const int base = 131;
int n, ans;
string s, now;
stack<int> st;
unordered_map<ull, int> mp;
set<ull> se;
ull get_hash(string s){
ull has = 0;
for (int i = 0; i < s.size(); i++){
has = has * base + s[i];
}
return has;
}
signed main(){
//freopen("P9753_11.in", "r", stdin);
//freopen("P9753_11.out", "w", stdout);
cin >> n >> s;
mp[0]++;
for (int i = 0; i < n; i++){
if (!st.empty() && st.top() == s[i] - 'a' + 1){
now.pop_back();
//cout << now << endl;
ull h = get_hash(now);
mp[h]++;
st.pop();
se.insert(h);
}else{
st.push(s[i] - 'a' + 1);
now += s[i];
//cout << now << endl;
ull h = get_hash(now);
mp[h]++;
se.insert(h);
}
}
for (auto it = se.begin(); it != se.end(); it++){
int k = mp[*it];
//cout << *it << " " << k << endl;
ans += (k * (k - 1)) / 2;
}
cout << ans;
return 0;
}