01背包问题

1.蛮力法求解0/1背包问题:(可能会超时,只是列出来供学习)

1)基本思想:

对于有n种可选物品的0/1背包问题,其解空间由长度为n0-1向量组成,可用子集数表示。在搜索解空间树时,深度优先遍历,搜索每一个结点,无论是否可能产生最优解,都遍历至叶子结点,记录每次得到的装入总价值,然后记录遍历过的最大价值。

==============================

#include <iostream>
#include<cstdio>
using namespace std;
#define N 100
struct goods{int wight;//物品重量int value;//物品价值};
int n,bestValue,cv,cw,C;//物品数量,价值最大,当前价值,当前重量,背包容量int X[N],cx[N];//最终存储状态,当前存储状态
struct goods goods[N];
int Force(int i){if(i>n-1){
    if(bestValue < cv && cw  <= C){
        for(int k=0;k<n;k++)
            X[k] = cx[k];//存储最优路径
        bestValue = cv;
    }
    return bestValue;
}
cw = cw + goods[i].wight;
cv = cv + goods[i].value;
cx[i] = 1;//装入背包
Force(i+1);
cw = cw-goods[i].wight;
cv = cv-goods[i].value;
cx[i] = 0;//不装入背包
Force(i+1);return bestValue;
}
int main()
{
    printf("物品种类n:");
    scanf("%d",&n);
    printf("背包容量C:");
    scanf("%d",&C);
    for(int i=0;i<n;i++){
        printf("物品%d的重量w[%d]及其价值v[%d]:",i+1,i+1,i+1);
        scanf("%d%d",&goods[i].wight,&goods[i].value);
    }
    int sum1 = Force(0);
    printf("蛮力法求解0/1背包问题:
X=[");
    for(int i=0;i<n;i++){
        cout << X[i]<<" ";
        }
        printf("] 装入总价值%d
",sum1);
    return 0;
}

2.动态规划法求解0/1背包问题:

 

 

 代码如下

#include <iostream>
#include<cstdio>
#define N 100
#define MAX(a,b) a < b ? b : a
using namespace std;

struct goods{
int wight;//物品重量
int value;//物品价值
};

int n,bestValue,cv,cw,C;//物品数量,价值最大,当前价值,当前重量,背包容量
int X[N],cx[N];//最终存储状态,当前存储状态
struct goods goods[N];

int KnapSack(int n,struct goods a[],int C,int x[]){
    int V[N][10*N];
    for(int i = 0; i <= n; i++)//初始化第0列
        V[i][0] = 0;
    for(int j = 0; j <= C; j++)//初始化第0行
        V[0][j] = 0;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= C; j++)
        if(j < a[i-1].wight)
            V[i][j] = V[i-1][j];
        else
            V[i][j] = MAX(V[i-1][j],V[i-1][j-a[i-1].wight] + a[i-1].value);

    for(int i = n,j = C; i > 0; i--){
        if(V[i][j] > V[i-1][j]){
            x[i-1] = 1;
            j = j - a[i-1].wight;
        }
        else
            x[i-1] = 0;
    }
    return V[n][C];
}
int main()
{
    printf("物品种类n:");
    scanf("%d",&n);
    printf("背包容量C:");
    scanf("%d",&C);
    for(int i = 0; i < n; i++){
        printf("物品%d的重量w[%d]及其价值v[%d]:",i+1,i+1,i+1);
        scanf("%d%d",&goods[i].wight,&goods[i].value);
    }
    int sum2 = KnapSack(n,goods,C,X);
     printf("动态规划法求解0/1背包问题:
X=[");
     for(int i = 0; i < n; i++)
        cout<<X[i]<<" ";//输出所求X[n]矩阵
     printf("]   装入总价值%d
", sum2);
     return 0;
}
原文地址:https://www.cnblogs.com/wxx23-IOU/p/13629706.html