HDU 3466 Proud Merchants(01背包)

题目链接: 传送门

Proud Merchants

Time Limit: 1000MS     Memory Limit: 65536K

Description

Recently, iSea went to an ancient country. For such a long time, it was the most wealthy and powerful kingdom in the world. As a result, the people in this country are still very proud even if their nation hasn’t been so wealthy any more.
The merchants were the most typical, each of them only sold exactly one item, the price was Pi, but they would refuse to make a trade with you if your money were less than Qi, and iSea evaluated every item a value Vi.
If he had M units of money, what’s the maximum value iSea could get?

Input

There are several test cases in the input.
Each test case begin with two integers N, M (1 ≤ N ≤ 500, 1 ≤ M ≤ 5000), indicating the items’ number and the initial money.
Then N lines follow, each line contains three numbers Pi, Qi and Vi (1 ≤ Pi ≤ Qi ≤ 100, 1 ≤ Vi ≤ 1000), their meaning is in the description.
The input terminates by end of file marker.

Output

For each test case, output one integer, indicating maximum value iSea could get.

Sample Iutput

2 10
10 15 10
5 10 5
3 10
5 10 5
3 5 6
2 7 3

Sample Output

5
11

解题思路

题目大意:有n个商品m块钱,给出买每个商品所花费的钱P、钱包里需要至少Q才有资格买、商品的价值V。问你如何购买商品的价值最大。
考虑下面的例子:A:p1=5, q1=10, v1=5; B:p2=3, q2=5, v2=6; 如果先买物品A再买物品B的话我至少需要10元钱,也就是money >= p1+q2,如果先买物品B再买物品A的话,我们至少需要13元钱,也就是money >= p2+q1。得到相同的价值的物品,我们却需要两个不同价值的钱,当然我们选择要花少的钱购买相同价值的商品了!
所以应使p1+q2 < p2+q1,交换位置p1-q1 < p2 - q2

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct Node{
	int p,q,v;
};

bool cmp(Node x,Node y)
{
	return (x.q - x.p) < (y.q - y.p);
}


int main()
{
	int N,M;
	while (~scanf("%d%d",&N,&M))
	{
		Node node[505];
		int dp[5005];
		memset(dp,0,sizeof(dp));
		memset(node,0,sizeof(node));
		for (int i = 0;i < N;i++)
		{
			scanf("%d%d%d",&node[i].p,&node[i].q,&node[i].v);
		}
		sort(node,node+N,cmp);
		for(int i = 0;i < N;i++)
		{
			for (int j = M;j >= node[i].q;j--)
			{
				dp[j] = max(dp[j-node[i].p] + node[i].v,dp[j]);
			}
		}
		printf("%d\n",dp[M]);
	}
	return 0;
}
posted @   zxzhang  阅读(178)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航