zoukankan      html  css  js  c++  java
  • 数据结构 —— 回溯法01背包

    今日一言:
    - 你轻视了什么最不应该轻视的东西?
    - 充足的睡眠。

    数据结构 —— 回溯法01背包


    回溯法

    /*********************************
     *
     * 回溯法 01背包 
     * create: 2020年6月1日 18点14分
     * author: LOS 
     *
     *********************************/

    #include <stdio.h>
    #include <string.h>

    #define BAG_SIZE 10 // 书包大小 
    #define TS_SIZE 7 // 珍宝数量 

    typedef struct { // treasure 
        int value; // 价值
        int weight; // 重量 
    } Ts;

    Ts treasures[] = {1,23,63,21,55,45,42,1};

    struct {
        int curValue; // 现有价值 
        int curWeight; // 现承重 
        int path[TS_SIZE]; // 路径 0为不拿 1是拿 
    } bag,caBag; // 背包以及缓存 

    void init(){

        bag.curValue = 0;
        caBag.curValue = 0;
        memset(caBag.path,0,sizeof(caBag.path));

    }

    void trackBack(int layer)// -1是根 0是第一件物品(根为假想的存在) 
        int i;

        if( layer == TS_SIZE ) { // 到底了就可以结束了
            printf("value: caBag --> %d ",caBag.curValue); // 记录可能的结果,验证答案用
            return;
        }


        if( layer == 0 ) {
            init(); // 初次回溯初始化一下变量 
        }

        if( bag.curValue < caBag.curValue ){
            // bag励志要和caBag一样富有
            bag.curValue = caBag.curValue;
            bag.curWeight = caBag.curWeight;
            for ( i = 0 ; i < BAG_SIZE ; i++ ){
                bag.path[i] = caBag.path[i];
            }
        }

        if( caBag.curWeight + treasures[layer].weight <= BAG_SIZE ){ // 装得下   先拿了再说
            caBag.curValue += treasures[layer].value;
            caBag.curWeight += treasures[layer].weight;
            caBag.path[layer] = 1// 1代表拿下了
            trackBack(layer+1); // 拿完就跑 
            caBag.curValue -= treasures[layer].value; // 回来了还是得交出来再说
            caBag.curWeight -= treasures[layer].weight;
            caBag.path[layer] = 0;
            trackBack(layer+1); // 交出来了还是得再走一次 
        } else { // 装不下就看看后面还能不能装 
            caBag.path[layer] = 0;
            trackBack(layer + 1);
        }

    }

    void main(){
        int i;

        trackBack(0);
        printf("value: bag --> %d ",bag.curValue);
        printf("weight: bag --> %d ",bag.curWeight);
        printf("path: bag --> ");
        for ( i = 0 ; i < BAG_SIZE ; i++ ){
            printf("%d",bag.path[i]);
        }
        printf(" ");

    }

  • 相关阅读:
    表的相关操作
    存储引擎介绍
    库的相关操作
    初始数据库
    linux版本的mysql安装
    mysql在windows上的安装即配置
    线程实际操作篇
    用户模板和用户场景
    顶会热词统计
    移动端疫情展示
  • 原文地址:https://www.cnblogs.com/rcklos/p/13027429.html
Copyright © 2011-2022 走看看