A and B and Interesting Substrings(dp)

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章