用Java写一个贪心算法
时间: 2024-05-06 12:18:20 浏览: 10
下面是一个 Java 实现的贪心算法示例,用于求解背包问题:
```java
import java.util.*;
public class GreedyAlgorithm {
public static void main(String[] args) {
int[] weights = {10, 20, 30};
int[] values = {60, 100, 120};
int capacity = 50;
int maxValue = getMaxValue(weights, values, capacity);
System.out.println("Max value: " + maxValue);
}
public static int getMaxValue(int[] weights, int[] values, int capacity) {
int n = weights.length;
Item[] items = new Item[n];
for (int i = 0; i < n; i++) {
items[i] = new Item(weights[i], values[i]);
}
Arrays.sort(items, Collections.reverseOrder());
int maxValue = 0;
for (int i = 0; i < n; i++) {
int w = items[i].weight;
int v = items[i].value;
if (capacity >= w) {
capacity -= w;
maxValue += v;
} else {
double fraction = (double) capacity / (double) w;
maxValue += fraction * v;
break;
}
}
return maxValue;
}
static class Item implements Comparable<Item> {
int weight;
int value;
public Item(int weight, int value) {
this.weight = weight;
this.value = value;
}
@Override
public int compareTo(Item other) {
double ratio = (double) value / (double) weight;
double otherRatio = (double) other.value / (double) other.weight;
return Double.compare(ratio, otherRatio);
}
}
}
```
在这个示例中,我们使用贪心策略来解决背包问题。我们首先将物品按照单位价值从高到低进行排序,然后依次选择物品,直到背包的容量不足以装下下一个物品为止。如果当前物品可以完全装入背包中,则将其全部装入;否则,我们将只装入一部分物品,使得背包装满。最后,我们返回所有选中物品的总价值。
在这个示例中,我们使用了一个内部类 Item 来表示物品,它包含两个属性:weight 和 value。我们还实现了 Comparable 接口,并重写了 compareTo 方法,以便在排序时按照单位价值从高到低进行排序。