Lotus has n 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 ≥0 。 InputFirst line is T(0≤T≤1000) T(0≤T≤1000) denoting the number of test cases. For each test case,first line is an integer n(1≤n≤26) n(1≤n≤26) ,followed by n n lines each containing 2 integers val i ,cnt i (|val i |,cnt i ≤100) vali,cnti(|vali|,cnti≤100) ,denoting the value and the amount of the ith character. OutputFor each test case.output one line containing a single integer,denoting the answer. Sample Input2 2 5 1 6 2 3 -5 3 2 1 1 1 Sample Output 35 5 题意:第一行T代表测试用例,然后每个测试用例第一行n代表接下来几行,每行第一个数为这个数的大小,第二个数代表这个数的数量。你所求的是怎样使数的总和最大。例如: 5 1 6 2 35=5*1+6*2+6*3; 5=1*1+2*2; 你懂得,不用解释。 思路:直接去想恐怕很难想,我刚开始想的就是先将大于零的从小到大排这样肯定是最大的,但是考虑到负数,想在前面在加几个负数才能使现在的总和大于原来的总和。但是有点难,所以想到用逆向思维。首先设一个up和一个ans(int)初始化为0,然后将这些数排序接着…….算了看代码吧 AC代码:
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;struct nose{ int a,b;}a[100005];int cmp(nose A,nose B){ return A.a>B.a;}int main(){ int T; scanf("%d",&T); while(T--) { int n; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d%d",&a[i].a,&a[i].b); } sort(a,a+n,cmp); int up=0,ans=0; for(int i=0;i<n;i++) { for(int j=0;j<a[i].b;j++) { if(up+a[i].a>0) { up+=a[i].a; ans+=up; } } } PRintf("%d/n",ans); } return 0;}新闻热点
疑难解答