【算法实验项目】背包问题(c++)

给定n个物品和一个容量为C的背包,物品i的重量是wi,其价值为vi。背包问题是如何选择装入背包的物品,使得装入背包中的物品总价值最大?(物品可以分割)

Input

单组数据输入。
第一行:两个整数n和C。表示物品的个数和背包的容量。(1≤n≤1000,0≤C≤100000)
下面有n行,每行有两个整数wi和vi,分别表示每个物品的重量和价值。(0≤wi≤1000,0≤vi≤1000)
 

Output

第一行:一个浮点数,表示能装入背包的最大价值V。V保留小数点后两位
第二行:n个整数,表示n个物品装入背包的重量。并以空格隔开。(按输入顺序排列,即第一个数为物品1装入背包的重量)

Sample Input

3 50
20 60
30 120
10 50

Sample Output

200.00
10 30 10

Hint

贪心策略
10×3+30×4+10×5=200

 

ac代码:

#include <bits/stdc++.h>
using namespace std;
struct hhh{
	double w,v,d=-1;
	int in=0,cut=0;
};
bool cmp(hhh x,hhh y){//按单位质量价值排序 
	return x.d>y.d;
}
bool cmp2(hhh x,hhh y){
	return x.in<y.in;
}
int main(){
	int n,i,j;
	double c;
	double res=0;
	cin>>n>>c;
	hhh a[n];
	for(i=0;i<n;i++){
  		cin>>a[i].w>>a[i].v;
  		a[i].in=i;//记录顺序 
  		if(a[i].w!=0)
  			a[i].d=a[i].v/a[i].w;
	}
	sort(a,a+n,cmp);
	for(i=0;i<n;i++)
		if(a[i].w==0)//将质量为0的物品放入背包 
     		res+=a[i].v;
	for(i=0;i<n;i++){
		if(a[i].w==0)
   			continue;
		if(a[i].w<c){//将整体能放进去的放入背包 
			c=c-a[i].w;
			res+=a[i].v;
			a[i].cut=a[i].w;
		}
		else{//将不能整体放入的背包分割放入 
			res+=c*a[i].d;
			a[i].cut=c;
			break;
		}
	}
	printf("%.2lf\n",res);
	sort(a,a+n,cmp2);//回到原本的排序
	//输出装入背包的物品质量 
	for(i=0;i<n;i++){ 
    	if(i)
    		cout<<" "<<a[i].cut;
    	else 
      		cout<<a[i].cut;
	}
	cout<<endl;
	return 0;
}

可分割的背包问题重点在排序。

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用贪心算法解决普通背包问题C++代码: ```cpp #include <iostream> #include <algorithm> using namespace std; struct goods { int weight; int value; double ratio; }; bool cmp(goods a, goods b) { return a.ratio > b.ratio; } double knapsack(goods* items, int n, int capacity) { sort(items, items + n, cmp); int current_weight = 0; double current_value = 0.0; for (int i = 0; i < n; ++i) { if (current_weight + items[i].weight <= capacity) { current_weight += items[i].weight; current_value += items[i].value; } else { int remaining_capacity = capacity - current_weight; current_value += items[i].ratio * remaining_capacity; break; } } return current_value; } int main() { int n, capacity; cout << "请输入物品数量和背包容量:" << endl; cin >> n >> capacity; goods* items = new goods[n]; cout << "请输入每个物品重量和价值:" << endl; for (int i = 0; i < n; ++i) { cin >> items[i].weight >> items[i].value; items[i].ratio = (double)items[i].value / items[i].weight; } double result = knapsack(items, n, capacity); cout << "可以装进背包的最大价值为:" << result << endl; delete[] items; return 0; } ``` 在此代码中,我们定义了一个结构体 `goods` 来表示物品,其中包括重量、价值和价值与重量比值三个成员变量。在 `cmp` 函数中,我们按照价值与重量比值从大到小排序。在 `knapsack` 函数中,我们首先对物品数组按照价值与重量比值从大到小排序,然后从大到小依次将物品放入背包中,直到背包装满为止。如果当前物品不能完全放入背包中,则将其部分放入背包中,并相应地计算价值。最后返回背包中的总价值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值