数据结构 —— 回溯法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\n",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\n",bag.curValue);
    printf("weight: bag --> %d\n",bag.curWeight);
    printf("path: bag --> ");
    for ( i = 0 ; i < BAG_SIZE ; i++ ){
        printf("%d",bag.path[i]);
    }
    printf("\n");

}

posted @ 2020-06-01 20:58  RCKLOS  阅读(360)  评论(0)    收藏  举报