hdu6011 Lotus and Characters 思路及题解

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

思路

这道题的话,他是要用字符构建字符串实现最大值,每个字符有不同的价值和个数,每个字符的价值在不同的位数乘以对应的值。
我的思路:首先想到把价值从大到小排列,因为最大的价值肯定是要放在最后一位的,这样实现价值最大化。每个字符的排列,肯定是从小到大排列的,这样才能保证最大值。但是这样的话,需要注意一个问题,当负数足够小的时候,他放在前面,反而整个字符串的价值会变大。基于这个观点,可以进行观察,当把一位负数放在首位的话,后面的数都向后移了一位,也就是说,之前再字符串每个字符的权值都变大了1。举个例子,-1 2 2 和 2 2,前面是-1+4+6,后面是2+4 。2 2的这个区间扩大了2+2,因此的话,可以用一个很简便的方法(最开始我是想到枚举的,发现有点烦琐)。用一个变量border记录当前所有数字的和,当他小于0的时候,则说明这个时候负数已经过大,不能再加负数进来了。例如-2 -1 1 2 这样的话,刚好是相加为0,他的值也和1 2字符串相等。接着,代码就可以写完了…

代码

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1001;
struct node
{
	int value;		// 字母价值
	int num;		//字母个数
};
bool cmp(node n1,node n2)
{
	return n1.value > n2.value;
}
int main()
{
	int t;
	cin >> t;
	int n, max_value;
	while (t--)
	{
		cin >> n;
		max_value = 0;
		node nodes[maxn];
		for (int i = 0; i < n; ++i)
		{
			cin >> nodes[i].value >> nodes[i].num;
		}
		//border代表临界条件
		int border=0;
		
		sort(nodes, nodes + n, cmp);

		
		for (int i = 0; i <n;++i)
		{
			for (int j = 0; j < nodes[i].num; ++j)
			{
				//代码优化后,最初用的是枚举法,依次进行判断
				border = border + nodes[i].value;
				//如果小于0,则说明这个负数过大,之后的负数也不考虑
				if (border < 0)
					break;
				max_value = border + max_value;
			}
		}
		
		cout << max_value << endl;
	}


	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值