HDU3732 - Ahui Writes Word - 动态规划之多重背包+二进制优化【经典】

本文解析了AhuiWritesWord问题,介绍了如何通过将多重背包问题转化为01背包问题并使用二进制优化来解决该问题,以求得在限定复杂度内单词的最大价值。

1.题目描述:

Ahui Writes Word

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3080    Accepted Submission(s): 1085


Problem Description
We all know that English is very important, so Ahui strive for this in order to learn more English words. To know that word has its value and complexity of writing (the length of each word does not exceed 10 by only lowercase letters), Ahui wrote the complexity of the total is less than or equal to C.
Question: the maximum value Ahui can get.
Note: input words will not be the same.
 

Input
The first line of each test case are two integer N , C, representing the number of Ahui’s words and the total complexity of written words. (1 ≤ N ≤ 100000, 1 ≤ C ≤ 10000)
Each of the next N line are a string and two integer, representing the word, the value(Vi ) and the complexity(Ci ). (0 ≤ Vi , Ci ≤ 10)
 

Output
Output the maximum value in a single line for each test case.
 

Sample Input
  
5 20 go 5 8 think 3 7 big 7 4 read 2 6 write 3 5
 

Sample Output
  
15
Hint
Input data is huge,please use “scanf(“%s”,s)”
 

Author
Ahui
 

Source
 

Recommend
notonlysuccess
 

2.题意概述:

给出一堆单词,每个单词有val (价值)、cos (复杂度),问消耗c的复杂度能够获得的最大价值。

3.解题思路:

就是一个多重背包问题,开始用01背包交果断超时,这时候学以致用,可以把多重背包拆分为二进制,也是一道经典的多重背包应用。

4.AC代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
#define maxn 10100
#define N 15
using namespace std;
int dp[maxn], weight[maxn], value[maxn], num[N][N];

int main()
{
	int n, c;
	while (scanf("%d%d", &n, &c) != EOF)
	{
		int val, price, cnt = 0;
		char ch[15];
		memset(dp, 0, sizeof(dp));
		memset(weight, 0, sizeof(weight));
		memset(value, 0, sizeof(value));
		memset(num, 0, sizeof(num));
		for (int i = 1; i <= n; i++)
		{
			scanf("%s%d%d", ch, &val, &price);
			num[val][price]++;
		}
		/*二进制大法好*/
		for (int i = 0; i <= 10; i++)
			for (int j = 0; j <= 10; j++)
			{
				int tmp = num[i][j];
				for (int k = 1; k <= tmp; k *= 2)
				{
					value[cnt] = i * k;
					weight[cnt++] = j * k;
					tmp -= k;
				}
				if (tmp)
				{
					value[cnt] = i * tmp;
					weight[cnt++] = j * tmp;
				}
			}
		for (int i = 0; i < cnt; i++)
			for (int j = c; j >= weight[i]; j--)
				dp[j] = max(dp[j - weight[i]] + value[i], dp[j]);  // 对于每件物品尝试拿与不拿
		printf("%d\n", dp[c]);
	}
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值