You are given a string s consisting of lower case letters. We assign the letters ‘a’ to ‘z’ values of 1 to 26, respectively. We will denote the value assigned to the letter X by val[X]. For example, val[‘a’] = 1 and val[‘e’] = 5.
We define the value of the string s as follows. For each letter s[i], let k[i] be the number of letters in s that are less than or equal to s[i], including s[i] itself. Then, the value of s is defined to be the sum of k[i] * val[s[i]] for all valid i.
Given the string, compute and return the value of the string.
Examples
0)
“babca”
Returns: 35
The value of this string is 2*4 + 1*2 + 2*4 + 3*5 + 1*2 = 35.
We can get the value as follows. The first character is a ‘b’ which has value 2, and has 4 characters that are less than or equal to it in the string (i.e. the first, second, third and fifth character of the string). Thus, this first character contributes 2*4 to the sum. We can derive a similar expression for each of the other characters.
1)
“zz”
Returns: 104
2)
“y”
Returns: 25
3)
“aaabbc”
Returns: 47
4)
“topcoder”
Returns: 558
5)
“thequickbrownfoxjumpsoverthelazydog”
Returns: 11187
6)
“zyxwvutsrqponmlkjihgfedcba”
Returns: 6201
【题目链接】:
【题解】
处理出每个字母出现的次数,然后对这个出现次数的字母求前缀和即可;
第一次打TP;
有点不习惯输入的方式;
要用return来输出;
其实还好;
就是要多写个类;
可以还按照原来的方式写,最后把int main那一段删掉就好;
【完整代码】
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <string>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
typedef pair<int,int> pii;
typedef pair<LL,LL> pll;
//const int MAXN = x;
const int dx[5] = {0,1,-1,0,0};
const int dy[5] = {0,0,0,-1,1};
const double pi = acos(-1.0);
class ValueOfString
{
public:
int findValue(string s)
{
int ans = 0;
int num[30]={0};
int len = s.size();
rep1(i,0,len-1)
num[s[i]-'a'+1]++;
rep1(i,1,26)
num[i] = num[i]+num[i-1];
rep1(i,0,len-1)
{
int val = s[i]-'a'+1;
ans += val*num[val];
}
return ans;
}
};
//最后交程序的时候把intmain以下删掉就好;
int main()
{
ValueOfString A;
string s;
cin >> s;
cout <<A. findValue(s);
return 0;
}