25分求助
查看原帖
25分求助
755408
__yabnto__楼主2023/11/5 11:39
#include <iostream>
#include <map>
#include <stack>

using namespace std;
using ll = long long;

const long long mod1 = 1e9 + 7, mod2 = 1e6 + 3, b = 127;

int n;
ll ans;
pair<ll, ll> sum;
map<pair<ll, ll>, int> st;
stack<int> s;

int main() {
  cin >> n;
  st[{0, 0}] = 1;
  for (int i = 1; i <= n; i++) {
    char c;
    cin >> c;
    if (!s.empty() && c == s.top()) {
      sum.first = (((sum.first - (c - 'a' + 1)) % mod1 + mod1) % mod1) / b;
      sum.second = (((sum.second - (c - 'a' + 1)) % mod2 + mod2) % mod2) / b;
      s.pop();
    } else {
      sum.first = ((sum.first * b) % mod1 + (c - 'a' + 1)) % mod1;
      sum.second = ((sum.second * b) % mod2 + (c - 'a' + 1)) % mod2;
      s.push(c);
    }
    ans += st[sum];
    st[sum]++;
  }
  cout << ans << endl;
  return 0;
}
2023/11/5 11:39
加载中...