写一个贪心算法的代码案例
时间: 2023-03-10 13:16:52 浏览: 77
下面是一个贪心算法的代码案例:def greedy_algorithm(items, max_weight):
result = [] # 存放最后结果
total_weight = 0 # 已选择物品的总重量 for item in items:
if total_weight + item.weight <= max_weight:
result.append(item)
total_weight += item.weight return result
相关问题
写一个贪心算法的Python代码案例
def greedyAlgorithm(values, weights, capacity):
# initialize total value and weight of knapsack to 0
totalValue = 0
totalWeight = 0
# loop through all items
for i in range(len(values)):
# if adding current item doesn't exceed capacity
if totalWeight + weights[i] <= capacity:
# add current item to the knapsack
totalWeight += weights[i]
totalValue += values[i]
# return total value of knapsack
return totalValue
# values of items
values = [60, 100, 120]
# weights of items
weights = [10, 20, 30]
# capacity of knapsack
capacity = 50
# call greedy algorithm function
print(greedyAlgorithm(values, weights, capacity))
提供一个贪心算法案例,Java代码
好的,这里给您提供一个贪心算法的经典案例——背包问题,以下是Java代码实现:
```java
public class KnapsackProblem {
public static int[] greedyKnapsack(int[] wt, int[] val, int capacity) {
int n = wt.length;
// calculating the value per unit weight
double[] ratio = new double[n];
for (int i = 0; i < n; i++) {
ratio[i] = (double) val[i] / wt[i];
}
// sorting the items in decreasing order of ratio (value per unit weight)
int[] index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
selectionSort(ratio, index);
// filling the knapsack using items in decreasing order of ratio (value per unit weight)
int[] result = new int[n];
int currentCapacity = 0;
for (int i = 0; i < n; i++) {
int itemIndex = index[i];
if (currentCapacity + wt[itemIndex] <= capacity) {
result[itemIndex] = 1;
currentCapacity += wt[itemIndex];
} else {
break;
}
}
return result;
}
// helper function for sorting the items based on ratio (value per unit weight)
public static void selectionSort(double[] arr, int[] index) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
swap(arr, i, maxIndex);
swap(index, i, maxIndex);
}
}
// helper function for swapping two items in an array
public static void swap(double[] arr, int i, int j) {
double temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// helper function for swapping two items in an array
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] wt = {10, 20, 30};
int[] val = {60, 100, 120};
int capacity = 50;
int[] result = greedyKnapsack(wt, val, capacity);
System.out.println("Items in the knapsack:");
for (int i = 0; i < result.length; i++) {
if (result[i] == 1) {
System.out.println("Item " + (i + 1));
}
}
}
}
```
以上代码实现了一个贪心算法解决背包问题,该算法将物品按照单位重量的价值从大到小排序,然后依次将价值高的物品放入背包中,直到背包装满为止。