Lotus and Characters
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/131072 K (Java/Others)Total Submission(s): 1211 Accepted Submission(s): 415
题目链接
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 。
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.
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题目翻译:第一行输入一个数代表测试数据的组数,然后下面一个n,代表下面将要输入n行信息,每行两个数,第一个数是第一个字符的价值,第二个是这个数字的个数。用这些字符可以组成很多字符串,这个字符串的价值的计算规则如下,第一个字符的价值*1+第二个字符的价值*2+...+第n个字符的价值*n,求字符串的最大价值。解题思路:这个题目是个思维题,感觉特别有意思,第一眼看到题目的时候很多人都会想,那只取所有的整数让大的整数靠后方就行了,然后会用题目中的测试数据一试,发现还真的都对哎。然后就动手写了,这时你就上当了。要知道题目既然给了负数,肯定不是白给的。如果上了这个当,只能说明你太单纯的去想负数可以拉低权值这件事情了。而且很容易就能给出一组测试数据把这个错误的想法推翻。例如测试样例:3-1 3 //3个-12 1 //1个21 1 //1个1如果按照只取正数的做法,则取的串为12,价值为1+2*2 = 5难道这真的是最优解吗?往下做做看吧。取序列 -1 1 2 ,则价值为 -1+1*2+2*3 = 7 哈哈大于5了,再往后看取序列 -1 -1 1 2 ,则价值为 -1+(-1*2)+1*3+2*4 = 8 哈哈又比7大了,再往后看吧取序列 -1 -1 -1 1 2 ,则价值为 -1 + (-1*2)+ (-1*3) + 1*4 + 2*5 = 8则最终答案就是8。这个例子很清晰的道出了原因,可以看出一个串的价值其实不单单又所谓的正整数去决定,决定串的价值的关键因素有两个,一个是数字,一个数串的长度,因为如果串的长度越长,则它越靠后面的正整数所乘的权值就会越大。因此负数的加入是可以增加字符串的长度的,能够使字符串后面乘的权值增大。现在来看一下具体的过程吧,我再在上面的测试数据加上一组数。如下4-10 2- 1 32 11 1则将这些数从小到大列出:- 10 -10 -1 -1 -1 1 2串长为1,则只有一个2 +2 = 2 > = 0串长为2,则有1,2 +1 +2 = 3 > = 0串长为3,则有-1,1,2 -1 +1 +2 = 2 > = 0串长为4,则有-1,-1,1,2 -1 -1 +1 +2 = 1 > = 0串长为5,则有-1,-1,-1,1,2 -1 -1 -1 +1 +2 = 0 > = 0串长为6,则有-10,-1,-1,-1,1,2 -10 -1 -1 -1 +1 +2 = -10 < 0到串为6的时候,它前面增加了一个-10后,前面负数总共是-13,而后面正数的增量才是3,已经不可能时串的值增加了,这是长度为5的串就是使串的价值最大的串,则其价值就是,2+3+2+1+0 = 8.#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<stdlib.h> #include<stack> #include<set> #include<queue> using namespace std; int a[100000]; int main() { int T,n,b,num; scanf("%d",&T); while(T--) { scanf("%d",&n); //输入n int i = 0,j; while(n--) { scanf("%d%d",&b,&num); //数字,该数字的个数 while(num--) { a[i++] = b; } } sort(a,a+i); //从小到大排序 int sum = 0,ans = 0; for(j = i-1; j >= 0; j--) { sum = sum + a[j]; if(sum < 0) break; ans += sum; } printf("%d\n",ans); } return 0; }