Lotus and Characters
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/131072 K (Java/Others)
Total Submission(s): 570 Accepted Submission(s): 213
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
题目翻译:http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=747&pid=1001
本题主要是要注意负数,如果只有正数就很好做,但是有的情况加入负数之后,最后的结果会更大,在网上找到下面的排序方法,依然是从小到大排序,但是累加的时候倒着算,如果总值开始变小,那么就跳出循环。
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t,n,va[2605];
scanf("%d",&t);
while(t--)
{
int i=0,a,b,sum=0;
scanf("%d",&n);
while(n--)
{
scanf("%d %d",&a,&b);
while(b--)
va[i++]=a;//储存所有数据
}
sort(va,va+i);
int cnt=i,last;
while(i--)
{
last=sum;
for(int j=i+1;j<cnt;j++)
sum=sum+va[j];//仔细体会,根据字母所在位置决定累加多少次
sum=sum+va[i];
if(sum<last)
{
sum=last;
break;//如果总值变小,跳出循环,最大值为上一个总值
}
}
if(sum<0)
sum=0;//题目中提到sum>=0;
printf("%d\n",sum);
}
return 0;
}