https://vjudge.net/problem/CodeForces-519Dhtml
給定每一個小寫字母一個數值,給定一個只包含小寫字母的字符串 s,求 s 的子串 t 個數,使 t知足:ios
考慮abca的值爲1 1 -1 1,前綴和爲1 2 1 0,用map維護每一個字符的各前綴和的個數,設兩個a位置分別爲l,r,那麼對於後一個a它的答案是map[a][preR],由於l+1~r-1的和爲0,因此pre[L]=pre[R-1]。c++
#include <bits/stdc++.h> using namespace std; #define inf 0x3f3f3f3f #define ll long long const int N = 200005; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1.0); #define lowbit(x) (x & (-x)) ll a[N], pre = 0; int main() { std::ios::sync_with_stdio(false); for (int i = 0; i < 26; i++) { cin >> a[i]; } string s; cin >> s; int l = s.length(); map<ll, ll> mp[27]; ll ans = 0; for (int i = 0; i < l; i++) { int c = s[i] - 'a'; ans += mp[c][pre]; pre += a[c]; mp[c][pre]++; } cout << ans << endl; return 0; }