蛮力法解决0_1背包问题新思路-——利用C语言位域类型

废话不说了,直接上代码

#include<stdio.h>
#include<math.h>
#define N 5  //物品种类数目
#define CAPACITY 6  //背包容量
#define COUNT  32
int weight[N]={3,2,1,4,5};
int value[N]={25,20,15,40,50};
union{
	unsigned char state;
	struct _FLAG{
	unsigned char good_1_flag:1;
	unsigned char good_2_flag:1;
	unsigned char good_3_flag:1;
	unsigned char good_4_flag:1;
	unsigned char good_5_flag:1;
	}flags;
}package;
int function()
{
	int sunw=0,sumv=0,maxValue=0;
	int totalWeight=0,totalValue=0,position,state;
	for(state=0;state<COUNT;state++)
	{
		package.state=state;
		totalWeight=package.flags.good_1_flag*weight[0]+package.flags.good_2_flag*weight[1]
			+package.flags.good_3_flag*weight[2]+package.flags.good_4_flag*weight[3]
			+package.flags.good_5_flag*weight[4];
		if(totalWeight<=CAPACITY)
		{
			totalValue=package.flags.good_1_flag*value[0]+package.flags.good_2_flag*value[1]
				+package.flags.good_3_flag*value[2]+package.flags.good_4_flag*value[3]
				+package.flags.good_5_flag*value[4];
			if(maxValue<totalValue)
			{
				maxValue=totalValue;
				position=state;
			}
		}
	}
	package.state=position;
	printf("maxValue=%d\ngood state:%d  %d   %d  %d  %d  \n",maxValue,package.flags.good_1_flag,
		package.flags.good_2_flag,package.flags.good_3_flag,package.flags.good_4_flag,package.flags.good_5_flag);
	return 0;
}

 运行结果

 

posted @ 2018-04-10 00:27  聊寂园  阅读(1993)  评论(0编辑  收藏  举报