《算法竞赛进阶指南》0x50背包 - 01背包

最大价值(贪心)
#include <bits/stdc++.h>
using namespace std;

int n, m;				//物品数量,背包容量 
struct info {
   
	double w, v, ratio;	//重量,价值 
}a[60];

bool cmp(info x, info y) {
   return x.ratio > y.ratio;}

int main() {
   
	cin >> n >> m;
	for (int i = 1; i <= n; i ++) {
   
		cin >> a[i].w >> a[i].v;
		a[i].ratio = a[i].v / a[i].w;
	}
	sort(a + 1, a + 1 + n, cmp);
	
	double w = 0, v = 0;
	for (int i = 1; i <= n; i ++) {
   
		if (w + a[i].w < m) {
   
			v += a[i].v;
			w += a[i].w;
		}
		else {
   
			v += a[i].ratio * (m - w);
			break;
		}
	}
	printf("%.2f", v);
	
	return 0;
}
01背包(模板题)
#include <bits/stdc++.h>
using namespace std;

int n, m;		
int f[209];

int main() {
   
	cin >> m >> n;
	
	for (int i = 1; i <= n; i ++) {
   
		int w, v;
		cin >> w >> v;
		for (int j = m; j >= w; j --) {
   
			f[j] = max(f[j], f[j - w] + v);
		}
	}
	cout << f[m];

	return 0;
}
集装箱装载
#include <bits/stdc++.h>
using namespace std;

int n, m;		
int f[33000];

int main() {
   
	cin >> n >> m;
	
	for (int i = 1; i <= n; i ++) {
   
		int w;
		cin >> w;
		for (int j = m; j >= w; j --) {
   
			f[j] = max(f[j], f[j - w] + w);
		}
	}
	cout << f[m];

	return 0;
}

/*
1 9
10
*/
#include <bits/stdc++.h>
using namespace std;

int n, m;		
bool f[33000];

int main() {
   
	cin >> n >> m;
	
	f[0] = true;
	for (int i = 1; i <= n; i ++) {
   
		int w;
		cin >> w;
		for (int j = m; j >= w; j --) {
   
			f[j] = f[j] || f[j - w];
		}
	}
	
	for (int j = m; j >= 0; j --) {
   
		if (f[j]) {
   
			cout << j;
			return 0;
		}
	}

	return 0;
}

/*
1 9
10
*/
小D的跨国贸易(贪心)
#include <bits/stdc++.h>
using namespace std;

int m, n, w[109];

int main() {
   
	cin >> m >> n;
	for (int i 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值