Lotus and Characters(贪心)
Lotus and Characters
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/131072 K (Java/Others)Total Submission(s): 1173 Accepted Submission(s): 406
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(0≤T≤1000) denoting the number of test cases.
For each test case,first line is an integer n(1≤n≤26),followed by n lines each containing 2 integers 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
题意
字符串的value计算方法是,把这些数字从小到大拍列起来,用他们本身的值乘以他们的下标,然后把它们都加起来 比如:1 2 3 3 value=1*1+2 *2+3 * 3 +3 * 4;求出用这些字符串所能构造的最大值。
分析
刚开始认为只把大于零的数字排序计算就行,而忽略了还要乘以下标,把负数或者零算进去的话,正数的下标就会增加,可能算上负数或者零会是整体的value增大。
把负数和非负数分别排序,按照规则把正数部分的value计算出来后,逐个的加上负数,若解果比原来的大,就可以把这个负数加上,否则就不必再计算了。
由于加上一个负数后的值就是把原先一系列的数的下标都向后移动一位,比如 value(原)=2 * 1+ 3 * 2+4* * 3 那么加上这个负数之后就是 value(现)=2 * 2+3 * 3+ 4 * 4 +a(负数)*1, value(现)-value(原)=2+3+4+a(负数);所以还需要用一个数来保存所有数的和。
代码
#include <iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int m;
scanf("%d",&m);
int a,b;
int mou[3000]= {0};
int fu[3000]= {0};
int j=0,k=0;
for(int i=0; i<m; i++)
{
scanf("%d%d",&a,&b);
if(a<0)
{
for(int i=0; i<b; i++)
{
fu[k++]=a;
}
}
else
{
for(int i=0; i<b; i++)
{
mou[j++]=a;
}
}
}
sort(mou,mou+j);
sort(fu,fu+k);
long long int sum=0;
int sum1=0;
for(int i=0; i<j; i++)
{
sum+=mou[i]*(i+1);
sum1+=mou[i];//保存所有非负数的和
}
for(int i=k-1; i>=0; i--)
{
if(fu[i]+sum+sum1>sum)//加上这个负数后与原来的值作比较
{
sum=sum+sum1+fu[i];
sum1=sum1+fu[i];//更新所有数的和
}
else
{
break;
}
}
printf("%lld\n",sum);
}
return 0;
}