主件 | 附件 |
电脑 | 打印机,扫描仪 |
书柜 | 图书 |
书桌 | 台灯,文具 |
工作椅 | 无 |
输入的第 1 行,为两个正整数,用一个空格隔开:N m
1000 5 800 2 0 400 5 1 300 5 1 400 3 0 500 2 0
2200
回溯法解法如下:
(该解法需要保证附件在主件的后面,否则附件永远都买不了【可以自己考虑重新排序,将主件都放在前面,附件都放在后面,不过很麻烦,没考虑那么多,暂时认为,输入的数据都是附件在主件的后面】)
//回溯法
#include
using namespace std;
//i:表示第i个物品(从0开始),x存储临时方法,rep表示剩余钱数,sum表示临时的总和,
//max存储最优的方法,number表示有几个物品,v表示价格,w表示重要度,maxsum存储最优总和,q表示是否为附件
void backtrack(int i,int* x,int rep,int sum,int* max,int number,int* v,int* w,int &maxsum,int* q) {
if (i == number) { //满足终止条件,判断是否为最优解,跳出迭代
if (sum > maxsum) {
maxsum = sum;
for (int j = 0; j < number; j++) { max[j] = x[j]; }
}
return;
}
if (v[i] <= rep&&(q[i] == 0 || x[q[i] - 1] == 1)) { //放的情况,然后走下一层
x[i] = 1;
rep -= v[i];
sum += v[i] * w[i];
backtrack(i+1,x,rep,sum,max,number,v,w,maxsum,q);
x[i] = 0;
rep += v[i];
sum -= v[i] * w[i];
}
backtrack(i + 1, x, rep, sum, max, number, v, w, maxsum,q); //不放的情况,然后走下一层
}
int main() {
int number;
int sumprice;
cin >> sumprice >> number;
int* v = new int[number];
int* w = new int[number];
int* x = new int[number];
int* max = new int[number];
int* q = new int[number];
for (int i = 0; i < number;i++) {
x[i] = 0;
}
for (int i = 0; i < number; i++) {
max[i] = 0;
}
for (int i = 0; i < number; i++) {
cin >> v[i] >> w[i] >> q[i];
}
int result = 0;
backtrack(0, x, sumprice, 0, max, number, v, w, result,q);
cout << result;
return 0;
}
然后是动态规划的方法,动态规划主要用到了一个求矩阵的公式:
r[i][j]=k,表示放i个物品,有j元钱的时候的最大的总和是k
r[i][j] = max(r[i - 1][j],r[i - 1][j - v[i]] + v[i] * w[i])
前者表示不放第i个物品,后者表示放第i个物品,两者取最大(最后得出正确的方法是刚好反着得到的)
代码如下:
//动态规划
#include
using namespace std;
void getx(int *x, int** r, int i, int j,int* v) {
for (; i>0&&j>0; i--) {
if (r[i][j] == r[i - 1][j]) {
x[i] = 0;
}
else {
j = j - v[i];
x[i] = 1; }
}
}
int main() {
int number;
int sumprice;
cin >> sumprice >> number;
int* x = new int[number + 1];
int* v = new int[number + 1];
int* w = new int[number + 1];
int* q = new int[number + 1];
int* id = new int[number + 1];
for (int i = 1; i < number + 1; i++) {
x[i] = 0;
}
for (int i = 1; i < number + 1; i++) {
cin >> v[i] >> w[i] >> q[i];
id[i] = i;
}
int** r = new int*[number + 1];
for (int i = 0; i < number + 1; i++) {
r[i] = new int[sumprice + 1];
}
//初始化
for (int j = 0; j < sumprice + 1; j++) {
r[0][j] = 0;
}
for (int i = 0; i < number + 1; i++) {
r[i][0] = 0;
}
//求解,i从1开始
for (int i = 1; i < number + 1; i++) {
for (int j = 0; j < sumprice + 1;) {
getx(x, r, i - 1, j,v);
if (r[i - 1][j] > r[i - 1][j - v[i]] + v[i] * w[i]) { r[i][j] = r[i - 1][j]; }
else if (j >= v[i] && (q[i] == 0 || x[q[i]] == 1)) {
r[i][j] = r[i - 1][j - v[i]] + v[i] * w[i];
}
else {
r[i][j] = r[i - 1][j];
}
j += 1;
}
}
cout << r[number][sumprice];
//可得到最优的具体方法
getx(x, r, number, sumprice,v);
cout << endl;
for (int i = 1; i < number + 1; i++) { cout << x[i] << "-"; }
//释放内存
for (int i = 0; i < number + 1; i++) {
delete[] r[i];
}
delete[]r;
return 0;
}