HDU 6011

来源:互联网 发布:程序员开发手册 编辑:程序博客网 时间:2024/06/06 14:45

Lotus and Characters

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。

大致意思就是给你很多个数字,有正有负。将这些数字排列起来,第一位乘以1,第二位乘以2,第三位乘以三,……最后求和,要求和最大。当然,没必要把所有数字都放上去。

这个乘积和最大,自然想到排序不等式,然后,既然有数字可以不上,当然就要处理这种情况。

首先,所有的正数都会是结果变大,所以,必须取。
然后,较大的负数可以使正数的位变高,也会使结果变大。
再小一点的负数就没必取了。

以下贴上代码。

#include <cstdio>#include <algorithm>#include <iostream> using namespace std;struct node{    int val,cnt;}a[30000];int c[30000];bool comp(node a,node b){return a.val<b.val;}int main(){    int T,n,top;    long long ans,now,tmp;    scanf("%d",&T);    while(T--){        scanf("%d",&n);        for(int i=1;i<=n;i++) scanf("%d%d",&a[i].val,&a[i].cnt);        sort(a+1,a+1+n,comp);        top = 0;        ans = 0;        now = 0;        for(int i=1;i<=n;i++){            for(int j=1;j<=a[i].cnt;j++){                c[++top] = a[i].val;                ans += a[i].val*top;                now += a[i].val;            }        }        tmp = ans;        for(int i=1;i<=top;i++){            if(c[i]>=0) break;            tmp -= now;            now -= c[i];            if(tmp > ans) ans = tmp;        }        cout<<ans<<endl;    }    return 0;} 
0 0
原创粉丝点击