算法杂谈--01背包

问题描述:给定一个载重为n的背包,现有m颗宝石,宝石具有重量和价值,现在往背包放宝石,让其价值最大!

分析:假设背包重量为11,有5颗石头,重量和价值分别为(2,10),(3,7),(2,10),(6,12),(3,8)。设f(11,5)为背包载重为11,有5颗石头时的最大价值!现在把(2,10)这颗石头拿出来分析,如果此石头加入到背包中则f(11,5)=f(11-2,4)+10,因为此石头一旦加入,背包载重变为11-2,石头数量变为4,此时产生价值10;如果此石头不加入背包,f(11,5)=f(11,4)。以此递归,从而得到解。


#include "alcomm.h"

//石头包含重量和价值
typedef struct stone
{
	int weight;
	int value;
}stone;

//bgwit表示背包载重,s是数组,count是数组元素个数
int bag(int bgwit,stone *s,int count)
{
	assert(s!=NULL);
	//当只有一颗石头是,如果包不能容纳,返回0
	if(count==1&&s[0].weight>bgwit)return 0;
	//如果能容纳,返回石头价值
	else if(count==1&&s[0].weight<=bgwit)return s[0].value;
	//next保存剩余的石头(剔除元数组中第一颗石头)
	stone next[count-1];
	int i=0;
	for(i=1;i<count;i++)
	{
		next[i-1]=s[i];
	}
	//如果第一颗石头不加入背包的情况
	int noadd=bag(bgwit,next,count-1);
	int add=0;
	//如果第一颗石头加入背包的情况
	if(bgwit>=s[0].weight)
		add=s[0].value+bag(bgwit-s[0].weight,next,count-1);
	//两者取其大
	return add>noadd?add:noadd;
}

int main()
{
	int tweight,stonenum,i;
	printf("input the bag weight:");
	scanf("%d",&tweight);
	printf("input the stone number:");
	scanf("%d",&stonenum);
	stone s[stonenum];
	printf("input the stone weight:");
	for(i=0;i<stonenum;i++)
	{
		scanf("%d",&s[i].weight);
	}
	printf("input the stone value:");
	for(i=0;i<stonenum;i++)
	{
		scanf("%d",&s[i].value);
	}
	
	int maxValue=bag(tweight,s,stonenum);
	printf("The max value is:%d\n",maxValue);
	return 0;
}


运行结果


alcomm.h头文件

#ifndef _ALCOMM_H
#define _ALCOMM_H

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>

#endif


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值