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
。
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 val
i
,cnt
i
(|val
i
|,cnt
i
≤100)
,denoting
the value and the amount of the ith character.
For each test case,first line is an integer n(1≤n≤26)
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
355
题目大意: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; }