問題一:最優裝載問題
給定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;
}
}
}