A and B and Interesting Substrings(dp)

来源:互联网 发布:linux dump内存命令 编辑:程序博客网 时间:2024/04/27 14:04

A and B are preparing themselves for programming contests.

After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.

A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).

B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).

Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.

Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?

Input
The first line contains 26 integers xa, xb, …, xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, …, z respectively.

The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.

Output
Print the answer to the problem.

Sample test(s)
input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
xabcab
output
2
input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
aaa
output
2
Note
In the first sample test strings satisfying the condition above are abca and bcab.

In the second sample test strings satisfying the condition above are two occurences of aa.

有两个傻逼,一个喜欢子串,一个喜欢开头结尾一样字符的串,他们对每个字母定义了一个数值。
现在问满足这两个傻逼的要求,并且除去头尾字母,中间子母和为0的串的个数。

实在是不会= =,看了题解,自己对字符串真是好无力……前缀和什么的太弱了
其实题目的要求可以转化
…..x….x
就是对于第二个x的前缀和sum,之前x的前缀和中有多少个等于sum。(这样两个x中和一定是0,注意,第一个前缀和指得是从开头到x前一个字母的和,后一个前缀和的意思是指连上x的和)。
这样想到的话,加一个map映射就可以搞定了。

具体看一下代码,拿纸画一画就出来了。

#include<cstdio>#include<cstring>#include<iostream>#include<queue>#include<vector>#include<algorithm>#include<string>#include<cmath>#include<set>#include<map>#include<vector>using namespace std;typedef long long ll;const int inf = 0x3f3f3f3f;const int maxn = 1005;ll a[30];map<ll,ll>mp[30];char s[100005];int main(){    #ifdef LOCAL    freopen("C:\\Users\\巍巍\\Desktop\\in.txt","r",stdin);    //freopen("C:\\Users\\巍巍\\Desktop\\out.txt","w",stdout);    #endif // LOCAL    for(ll i = 1;i <= 26;i++)        scanf("%lld",&a[i]);    scanf("%s",s);    ll len = strlen(s);    ll sum = 0,ans = 0;    for(ll i = 0;i < len;i++)    {        if(mp[s[i] - 'a' + 1].count(sum))            ans += mp[s[i] - 'a' + 1][sum];        sum += a[s[i] - 'a' + 1];        mp[s[i] - 'a' + 1][sum]++;    }    printf("%lld\n",ans);    return 0;}
0 0
原创粉丝点击