您的位置:首页 > 其它

c 装载问题 回溯法

2011-04-21 18:38 316 查看
#include <stdio.h>

#include <stdlib.h>

typedef struct {

int* w;

int c ;

int cw;

int bestcw;

int n ;

}ship_info;

ship_info ship;

void BackTrace(int i);

void BackTrace(int i)

{

if(i > ship.n) return ;

if(i == ship.n){

if(ship.cw > ship.bestcw){

ship.bestcw = ship.cw;

}

}

if(ship.cw + ship.w[i] < ship.c){

ship.cw += ship.w[i];

BackTrace(i+1);

ship.cw -= ship.w[i];

}

BackTrace(i+1);

}

int main()

{

int temp[5] = {20, 15, 5, 2, 30};

ship.w = temp;

ship.c = 55;

ship.cw = 0;

ship.bestcw = 0;

ship.n =5;

BackTrace(0);

printf("%d", ship.bestcw);

system("pause");

return 0;

}

#######################################非递归

#include <stdio.h>

#include <stdlib.h>

typedef struct {

int* w;

int c ;

int cw;

int bestcw;

int n ;

int* x;

}ship_info;

ship_info ship;

void BackTrace(int i);

void BackTrace(int i)

{

while(1 == 1){

while(i < ship.n){

if(ship.cw + ship.w[i] < ship.c){

ship.x[i] = 1;

ship.cw += ship.w[i];

}

else{

ship.x[i] = 0;

}

i++;

};

if(i >= ship.n){

if(ship.cw > ship.bestcw){

ship.bestcw = ship.cw;

}

}

i--;

while(i > 0 && ship.x[i] == 0){

i--;

}

if(i == 0 ) return ship.bestcw;

if(ship.x[i] > 0) {

ship.cw -= ship.w[i];

ship.x[i] = 0;

}

i++;

}

}

int main()

{

int temp[5] = {20, 15, 5, 2, 30};

int temp1[5] = {0, 0, 0, 0, 0};

ship.w = temp;

ship.x = temp1;

ship.c = 55;

ship.cw = 0;

ship.bestcw = 0;

ship.n =5;

BackTrace(0);

printf("%d", ship.bestcw);

system("pause");

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: