0/1背包问题 - 回溯法(C++实现)

0/1背包问题 - 回溯法(C++实现)

flyfish

Backtracking is a general algorithm for finding all (or some) solutions to some computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons each partial candidate c (“backtracks”) as soon as it determines that c cannot possibly be completed to a valid solution

回溯法是查找计算问题的所有或者一些解决方案的通用算法。尤其constraint satisfaction problems(约束满足问题),逐步建立候选的解决方案,尽早抛弃无效的

解决方案

notably与particularly,especially是同义词

especially和specially之间的区别

通过实例区别
I liked all the children, Tom especially.我喜欢所有的孩子,特别是汤姆.
I don’t like bright color, especially red.我不喜欢鲜艳的颜色, 尤其是红色.

Those shoes were specially made for me.这双鞋是专门为我做的.
I made this specially for your birthday.这是我特意为你生日而做的
The ring was specially made for her.戒指是为她特制的

解决方案集合构成的一颗二叉树
0/1背包问题 - 回溯法(C++实现)_第1张图片
代码:VC++调试通过

#include "stdafx.h"
#include 
#include 
#include 

struct Item //物品定义
{
    int id, weight, value;//编号,重量,价值。编号为0的物品这里没有使用
    Item(){}
    Item(int i, int w, int v) :id(i), weight(w), value(v){}


    void operator += (const Item &i) //重载操作符主要是为计算使用
    {
        this->value = this->value + i.value;
        this->weight = this->weight + i.weight;
    }
    void operator -= (const Item &i)
    {
        this->value = this->value - i.value;
        this->weight = this->weight - i.weight;
    }
};



Item currentItem{ 0, 0, 0 };
const int n = 4, C = 10;
//C背包所能承受的最大重量
//物品个数n
int edge[n];  //记录树中的路径,1表示装入背包,0反之

std::vector allItems;//所有的物品
int maxValue = 0;//能够装入背包的最大价值

void Backtracking(int i)
{
    if (i >= n)//递归结束
    {
        if (currentItem.value > maxValue)
            maxValue = currentItem.value;

        return;
    }
    if (currentItem.weight + allItems[i].weight <= C)//边为1的子节点
    {
        edge[i] = 1;

        currentItem += allItems[i];
        Backtracking(i + 1);
        currentItem -= allItems[i];

    }
    else
    {
        edge[i] = 0;//边为0的子节点
        Backtracking(i + 1);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    allItems.push_back(Item(1, 3, 30));
    allItems.push_back(Item(2, 5, 20));
    allItems.push_back(Item(3, 4, 10));
    allItems.push_back(Item(4, 2, 40));
    Backtracking(0);


    for (int i = 0; i < n; i++)
    {
        if (edge[i] == 1)
        {
            std::cout << "物品编号:" << allItems[i].id
                << "  重量:" << allItems[i].weight
                << "  价值:" << allItems[i].value << std::endl;
        }
    }

    std::cout << "背包最大价值:" << maxValue;
    return 0;
}

你可能感兴趣的:(数据结构与算法设计)