几个背包相关的问题

问题一:最优装载问题
给定n个物体,第i个物体的重量是wi,选择尽量多的物体,使其重量不超过c

import java.util.Arrays;
import java.util.Scanner;

public class 最优装载问题 {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int[] w=new int[n];
		for (int i = 0; i < n; i++) {
			w[i]=sc.nextInt();
		}
		int c=sc.nextInt();
		Arrays.sort(w);
		int ans=f(n,w,c);
		System.out.println(ans);
	}

	private static int f(int n, int[] w, int c) {
		int sum=0;
		int cnt=0;
		for (int i = 0; i < n; i++) {
			sum+=w[i];
			if (sum<=c) {
				cnt++;
			}else
				break;
		}
		return cnt;
	}
	
	
}

问题二:部分背包问题
在这里插入图片描述

import java.util.Arrays;

public class 部分背包问题 {
	public static void main(String[] args) {
		int[] w= {1,2,3,4,5};
		int[] v= {3,4,3,1,4};
		int n=w.length;
		double c=10;//规定一个重量
		Obj[] objs=new Obj[n];
		for (int i = 0; i < n; i++) {
			objs[i]=new Obj(w[i],v[i]);//打包
		}
		
		Arrays.sort(objs);
		double cc=c;
		double maxValue=0;
		for (int i = n-1; i >=0; i--) {
			if (objs[i].w<=cc) {
				maxValue+=objs[i].v;
				cc-=objs[i].w;
			}else {
				maxValue+=objs[i].v*(cc/objs[i].w);//把缺少的那部分的重量所占的价格算进去
				break;
			}
		}
		System.out.println(maxValue);
	}
	private static class Obj implements Comparable<Obj>{
		int w;
		int v;
		public Obj(int w,int v) {
			this.w=w;
			this.v=v;
		}
		
		public double getPrice() {
			return v/(double) w;//计算单价
		}
		
		public int compareTo(Obj o) {
			if(this.getPrice()==o.getPrice()) return 0;
			else if(this.getPrice()<o.getPrice()) return -1;
			else return 1;
		}

	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值