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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章