hdu 6011 lotus and characters

来源:互联网 发布:日本尺八制作数据 编辑:程序博客网 时间:2024/05/16 08:55

Lotus has nn 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。
Input
First 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 nn lines each containing 2 integers vali,cnti(|vali|,cnti≤100)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
题意:字母排序,给出字符的价值和个数,字符串按顺序每一个x1,x2,x3递增,很明显应该把价值大的往后排,那么价值为负的怎么办,放前面还是不要,这取决于哪个值比较大,如果从前往后操作,因为不知道当前这个负值要不要所以很难操作,方法二排序后就是从后往前,因为最后面的正数必须是要的,然后用cnt存取已经存在的字符。 由于
如果样例是
3
a 1
b 1
c 1
c>b>a 那么结果应该是 a*1+b*2+c*3 =a+b+b+c+c+c,从后往前用cnt记录每次要增加的值,cnt = c, cnt=c+b,cnt=c+b+a; 而且记录增量的同时每次把增量加到 ans里面 就能得到一样的结果。因为c是*3 所以在每一个要加进去的数里面它都存在,同理,b只存在两次,a只存在1次。
所以得出结果是一样的。而且能解决在哪里停止的问题。

#include <bits/stdc++.h>using namespace std;pair <int,int > p[30];int main(){    int t;    cin>>t;    while(t--)    {        int n;        cin>>n;        for(int i=0;i<n;i++)        {            int a,b;            cin>>a>>b;            p[i]=make_pair(a,b);        }        long long cnt=0;        long long ans=0;        sort(p,p+n);        for(int i=n-1;i>=0;i--)        {            for(int j=0;j<p[i].second;j++)            {                cnt+=p[i].first;                if(cnt<0) break;                ans+=cnt;            }        }        cout<<ans<<endl;    }}
2 0