背包问题-优先对列式分支界限法

本文介绍了一种使用优先队列实现的0-1背包问题求解算法。通过定义节点结构体和优先级比较准则,该算法能够高效地找到最优解。在主函数中,通过初始化参数并调用最大背包容量计算函数,最终输出最佳价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>
using namespace std;
typedef struct Node{
        int cp;
        int cw;
        double up_p;
        int level;
        bool choose;
        Node * pre;
}Node;

const int n = 10;
int c = 0;
int w[n+1] = {0};
int p[n+1] = {0};
int cp = 0;
int cw = 0;
int bestp = 0;
bool bestx[n+1] = {0};

vector<Node*> heap;

void initParament()
{

}

bool compareNode(Node *node1, Node *node2)
{
        return node1->up_p > node2->up_p;
}
double bound(int level)
{
        int cleft = c - cw;
        double value = cp;
        int i = level;
        for(; i<=n; i++){
                if(w[i] <= cleft){
                        cleft -= w[i];
                        value += p[i];
                }else{
                        break;
                }
        }

        if(cleft > 0){
                value += double(cleft)/w[i] * p[i];
        }

        return value;

}
void insertNode(int cw, int cp ,int level, int up_p, Node * parent, bool choose)
{
        Node *new_node = new Node;
        new_node->cw = cw;
        new_node->cp = cp;
        new_node->level = level;
        new_node->up_p = up_p;
        new_node->pre = parent;
        new_node->choose = choose;

        heap.push_back(new_node);
        push_heap(heap.begin(), heap.end(), compareNode);
}

void deleteNode(Node ** current)
{
        if( heap.empty() ){
                current = NULL;
                return;
        }
        pop_heap(heap.begin(), heap.end(), compareNode);
        current = &(*heap.rbegin());
        heap.erase(heap.end()-1);
}
void maxKnapsack()
{
        Node *current = NULL;
        int i=1;
        while( i != n ){
                int wt = cw + w[i];
                if(wt < c){
                        bestp = max(bestp, cp+p[i]);
                        insertNode(wt, cp+p[i], i+1, bound(i), current, true);
                }
                double rest = bound(i+1);
                if(rest  > bestp){
                        insertNode(cw, cp, i+1, rest, current, false);
                }

                deleteNode(&current);
                assert(current);
                cp = current->cp;
                cw = current->cw;
                i = current->level;
        }
        for(int i=n; i>0 && current!=NULL; i--){
                bestx[i] = current->choose;
                current = current->pre;
        }
}



int main()
{
        initParament();

        maxKnapsack();

        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值