You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
#include <bits/stdc++.h>
|
|
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
#define maxV 1000
|
|
|
|
|
/*
|
|
|
|
|
1. 01背包
|
|
|
|
|
1)题目:
|
|
|
|
|
有n件物品和一个容量为v的背包。
|
|
|
|
|
第i件物品的费用是c[i],价值是w[i]。
|
|
|
|
|
求解将哪些物品装入背包可使价值总和最大
|
|
|
|
|
2)输入:
|
|
|
|
|
测试用例数
|
|
|
|
|
物品数 背包大小
|
|
|
|
|
n个物品的ci和wi
|
|
|
|
|
* */
|
|
|
|
|
int main(void) {
|
|
|
|
|
int times, n, v, ci, wi;
|
|
|
|
|
int f[maxV];
|
|
|
|
|
//读取数据文件
|
|
|
|
|
freopen("../1.txt", "r", stdin);
|
|
|
|
|
|
|
|
|
|
//读入次数
|
|
|
|
|
cin >> times; //本示例是2次
|
|
|
|
|
|
|
|
|
|
//开始两次循环
|
|
|
|
|
while (times--) {
|
|
|
|
|
//初始值
|
|
|
|
|
memset(f, 0, sizeof(f));
|
|
|
|
|
//读取物品个数与背包体积
|
|
|
|
|
cin >> n >> v;
|
|
|
|
|
//对每个物品进行读取判断
|
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
|
|
//第i件物品的费用(此例出指体积)是c[i],价值是w[i]。
|
|
|
|
|
cin >> ci >> wi;
|
|
|
|
|
//利用01背包模板进行填充f数组,动态规划
|
|
|
|
|
for (int j = v; j >= 0; j--) { //从大到小
|
|
|
|
|
if (j >= ci)
|
|
|
|
|
f[j] = max(f[j - ci] + wi, f[j]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
//输出动态规划的数组
|
|
|
|
|
for (int i = 0; i <= v; i++) {
|
|
|
|
|
cout << f[i] << " ";
|
|
|
|
|
}
|
|
|
|
|
cout << endl;
|
|
|
|
|
|
|
|
|
|
//最后的结果
|
|
|
|
|
cout << f[v] << endl;
|
|
|
|
|
}
|
|
|
|
|
}
|