通过写一个类,类中写上你要用到的参数,然后在主程序中创建该类的数组
下面举个例子
圣诞老人的礼物
题目描述:
圣诞节来临了,在城市A中圣诞老人准备分发糖果,现在有多箱不同的糖果,每箱糖果有自己的价值和重量,每箱糖果都可以拆分成任意散装组合带走。圣诞老人的驯鹿最多只能承受一定重量的糖果,请问圣诞老人最多能带走多大价值的糖果。
输入第一行由两个部分组成,分别为糖果箱数正整数n(1 <= n <= 100),驯鹿能承受的最大重量正整数w(0 < w < 10000),两个数用空格隔开。其余n行每行对应一箱糖果,由两部分组成,分别为一箱糖果的价值正整数v和重量正整数w,中间用空格隔开。输出输出圣诞老人能带走的糖果的最大总价值,保留1位小数。输出为一行,以换行符结束。
输入:
4 15 100 4 412 8 266 7 591 2
输出:
1193.0
主程序:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static int n,C;
public static Struct struct[];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
C = in.nextInt();
struct = new Struct[n];
for(int i=0;i<n;i++) {
int value = in.nextInt();
int weight = in.nextInt();
struct[i] = new Struct(value, weight, value*(1.0)/weight);
}
Comparator<Struct>comparator = new Mycomparator();
//sort排序方法的第二种用法,两个参数,重载compare函数,设置自己的比较方法
Arrays.sort(struct,comparator);
double totv = 0,totw = 0;
for(int i=0;i<n;i++) { //按单位重量的价值从大到小一次放入
if(totw + struct[i].getWeight() <= C) { //未放满
totv += struct[i].getValue();
totw += struct[i].getWeight();
}else {
totv += struct[i].getDesity() * (C-totw);
totw = C;
break;
}
}
System.out.printf("%.1f",totv);
}
}
//自定义的排序方法
class Mycomparator implements Comparator<Struct>
{
public int compare(Struct o1, Struct o2) { //降序
if(o1.getDesity()<o2.getDesity())
return 1;
else if(o1.getDesity()==o2.getDesity())
return 0;
else
return -1;
}
}
struct类:
public class Struct {
private int value;
private int weight;
private double desity;
public Struct(int value,int weight,double desity){
this.value = value;
this.weight = weight;
this.desity = desity;
}
public double getDesity() {
return desity;
}
public void setDesity(float desity) {
this.desity = desity;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}