hdu6011 -Lotus and Characters

Lotus and Characters

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/131072 K (Java/Others)
Total Submission(s): 1937    Accepted Submission(s): 648


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(0T1000) denoting the number of test cases.
For each test case,first line is an integer n(1n26),followed by n lines each containing 2 integers vali,cnti(|vali|,cnti100),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

题目大意:Lotus有n种字母,给出每种字母的价值以及每种字母的个数限制,她想构造一个任意长度的串。

定义串的价值为:第1位字母的价值*1+第2位字母的价值*2+第3位字母的价值*3……求Lotus能构造出的串的最大价值。

(可以构造空串,因此答案肯定≥0)例如第一个样例中有1个5,2个6构成字符串,最大的排序方法为5 6 6,即5×1+6×2+6×3=35。

解题思路: 从该题来看,应该把字母从小往大放。 不过错误的想法是将负数剔除然后只加正数(一开始我就这么做的,结果一直WA)。

错误是因为负数也可能出现在答案中:放在最前面来使后面每个字母的贡献都增加例如-1*1+2*2大于2*1。

正确的做法是把字母从大往小从后往前放,如果加入该字母后答案出现减小情况就停下来。

#include <iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node
{
    int x;
    int y;

}p[30];
int cmp(const node &a,const node &b)
{
        return a.x>b.x;
}
int main()
{
    int i,j;
    int t,n;
   cin>>t;
    while(t--)
    {
        cin>>n;
        for(i=0;i<n;i++)
        {
            cin>>p[i].x>>p[i].y;
        }
        int ans=0;
        int num=0;
        sort(p,p+n,cmp);
        for(i=0;i<n;i++)
        {
            for(j=0;j<p[i].y;j++)
            {
                num+=p[i].x;
                if(num>0)
                {
                    ans+=num;
                }
                 else break;
            }

        }
        cout<<ans<<endl;
    }
    return 0;
}
本题还可以用数组做,思路类似
#include<iostream>
#include<algorithm>
using namespace std;
int a[10010];
int main()
{
   int t;
   cin>>t;
   while(t--)
   {
       int n;
       cin>>n;
       int ans=0;
       for(int i=0;i<n;i++)
       {
           int x,y;
           cin>>x>>y;
           while(y--)
           {
               a[ans]=x;
               ans++;
           }
       }
       sort(a,a+ans);
       int sum=0;
       int maxx=0;
       int num=0;
       for(int j=ans-1;j>=0;j--)
       {
           sum+=a[j]+num;
           num+=a[j];
           maxx=max(maxx,sum);
       }
       cout<<maxx<<endl;
   }
   return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值