赞
踩
1.设限重W,装入总价值cp,总重量cw.
2.需要设置布尔数组来储存物品的存放情况,0为无,1为有。
3.最优解bestp,最优方法bestb[n]
4.方法数组为bool型,输入数量为int型,重量和价值为double型。
注意:运行条件,终止条件
- #include<iostream>
- using namespace std;
-
- typedef struct sub {
- double weight;
- double value;
- }S;
-
- double bound(int i, S* s, double cp, int n);
- void Backrack(int i, bool* b, S* s, int n, double cp, double cw, double W, bool* bestb);
-
- double bestp = 0;
-
- int main() {
- double cp = 0, cw = 0;
- int n, W;
- cout << "输入数量和限重" << endl;
- cin >> n >> W;
- S* s = new S[n];
- bool* b = new bool[n];
- bool* bestb = new bool[n];
-
-
- cout << "输入价值,重量" << endl;
- for (int i = 0; i < n; i++) {
- cin >> s[i].value >> s[i].weight;
- }
- Backrack(0, b, s, n, cp, cw, W,bestb);
- cout << bestp<<endl;
- for (int i = 0; i < n; i++) {
- cout << bestb[i] << " ";
- }
- }
-
- double bound(int i, S* s, double cp, int n) {
- double rp=0;
- for (int j = i; j < n; j++) {
- rp += s[j].value;
- }
- return rp+cp;
- }
-
-
- void Backrack(int i, bool *b,S *s,int n,double cp,double cw,double W,bool *bestb) {
- if (i > n-1) {
- int c=0;
-
- if (cp > bestp) {
- bestp = cp;
- for (int i = 0; i < n; i++) {
- bestb[i] = b[i];
- }
- }
- return;
- }
- if (cw + s[i].weight <= W) {
- cp += s[i].value;
- cw += s[i].weight;
- b[i] = 1;
- Backrack(i + 1, b, s, n, cp, cw, W,bestb);
- cp -= s[i].value;
- cw -= s[i].weight;
- }
- if (bound(i + 1,s,cp,n) > bestp) {
- b[i] = 0;
- Backrack(i + 1, b, s, n, cp, cw, W,bestb);
- }
- }
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。