Lotus and Characters
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/131072 K (Java/Others)
Total Submission(s): 29 Accepted Submission(s): 13
Problem Description
Lotus has n kinds of characters,each kind of characters has a value and a amount.She wants to construct a string using some of these characters.Define the value of a string is:its first character’s value*1+its second character’s value *2+…She wants to calculate the maximum value of string she can construct.
Since it’s valid to construct an empty string,the answer is always ≥0。
Input
First line is T(0≤T≤1000) denoting the number of test cases.
For each test case,first line is an integer n(1≤n≤26),followed by n lines each containing 2 integers vali,cnti(|vali|,cnti≤100),denoting the value and the amount of the ith character.
Output
For each test case.output one line containing a single integer,denoting the answer.
Sample Input
2
2
5 1
6 2
3
-5 3
2 1
1 1
Sample Output
35
5
Source
BestCoder Round #91
题意 :Lotus有nnn种字母,给出每种字母的价值以及每种字母的个数限制,她想构造一个任意长度的串。定义串的价值为:第1位字母的价值*1+第2位字母的价值*2+第3位字母的价值*3……求Lotus能构造出的串的最大价值。(可以构造空串,因此答案肯定≥0\geq 0≥0)
思路 : 根据排序不等式,显然应该把字母从小往大放。 一种错误的做法是把正权值的字母取出来从前往后放。错误是因为负权的也可能出现在答案中:放在最前面来使后面每个字母的贡献都增加。 正确的做法是把字母从大往小从后往前放,如果加入该字母后答案变劣就停下来。
AC代码 :
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
pair <int,int> p[28];
int main()
{
int T,N,a,b;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
LL ans = 0,cut = 0;
for(int i = 1 ; i <= N; i++){
scanf("%d %d",&a,&b);
p[i] = make_pair(a,b);
}
sort(p + 1, p + 1 + N);
for(int i = N ; i >= 1; i--)
for(int j = p[i].second; j >= 1; j--){
cut += p[i].first;
if(cut < 0) break;
ans += cut;
}
printf("%lld\n",ans);
}
return 0;
}