cf519D. A and B and Interesting Substrings(前缀和)

题意

给出$26$个字母对应的权值和一个字符串

问满足以下条件的子串有多少

  1. 首尾字母相同
  2. 中间字母权值相加为0

Sol

我们要找到区间满足$sum[i] - sum[j] = 0$

$sum[i] = sum[j]$

开$26$个map维护一下$sum$相等的子串就可以

/*

*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<cmath>
//#include<ext/pb_ds/assoc_container.hpp>
//#include<ext/pb_ds/hash_policy.hpp>
#define Pair pair<int, int>
#define MP(x, y) make_pair(x, y)
#define fi first
#define se second
#define int long long 
#define LL long long 
#define ull unsigned long long 
#define rg register 
#define pt(x) printf("%d ", x);
//#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
//char buf[(1 << 22)], *p1 = buf, *p2 = buf;
//char obuf[1<<24], *O = obuf;
//void print(int x) {if(x > 9) print(x / 10); *O++ = x % 10 + '0';}
//#define OS  *O++ = ' ';
using namespace std;
//using namespace __gnu_pbds;
const int MAXN = 1e6 + 10, INF = 1e9 + 10, mod = 1e9 + 7;
const double eps = 1e-9;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int val[27];
char s[MAXN];
map<int, int> mp[27];
main() {
    for(int i = 1; i <= 26; i++) val[i] = read();
    scanf("%s", s + 1);
    int N = strlen(s + 1), ans = 0, sum = 0;
    for(int i = 1; i <= N; i++) {
        int x = s[i] - 'a' + 1;
        ans += mp[x][sum];
        sum += val[x];
        mp[x][sum]++;
    }
    printf("%I64d", ans);
    return 0;
}
/*

*/

 

posted @ 2018-09-03 16:44  自为风月马前卒  阅读(387)  评论(0编辑  收藏  举报

Contact with me