Files
hello-algo/ru/codes/java/chapter_greedy/fractional_knapsack.java
Yudong Jin 772183705e Add ru version (#1865)
* Add Russian docs site baseline

* Add Russian localized codebase

* Polish Russian code wording

* Update ru code translation.

* Update code translation and chapter covers.

* Fix pythontutor extraction.

* Add README and landing page.

* placeholder of profiles

* Use figures of English version

* Remove chapter paperbook
2026-03-28 04:24:07 +08:00

60 lines
2.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* File: fractional_knapsack.java
* Created Time: 2023-07-20
* Author: krahets (krahets@163.com)
*/
package chapter_greedy;
import java.util.Arrays;
import java.util.Comparator;
/* Предмет */
class Item {
int w; // Вес предмета
int v; // Стоимость предмета
public Item(int w, int v) {
this.w = w;
this.v = v;
}
}
public class fractional_knapsack {
/* Дробный рюкзак: жадный алгоритм */
static double fractionalKnapsack(int[] wgt, int[] val, int cap) {
// Создать список предметов с двумя свойствами: вес и стоимость
Item[] items = new Item[wgt.length];
for (int i = 0; i < wgt.length; i++) {
items[i] = new Item(wgt[i], val[i]);
}
// Отсортировать по удельной стоимости item.v / item.w в порядке убывания
Arrays.sort(items, Comparator.comparingDouble(item -> -((double) item.v / item.w)));
// Циклический жадный выбор
double res = 0;
for (Item item : items) {
if (item.w <= cap) {
// Если оставшейся вместимости достаточно, положить в рюкзак текущий предмет целиком
res += item.v;
cap -= item.w;
} else {
// Если оставшейся вместимости недостаточно, положить в рюкзак часть текущего предмета
res += (double) item.v / item.w * cap;
// Свободной вместимости больше не осталось, поэтому выйти из цикла
break;
}
}
return res;
}
public static void main(String[] args) {
int[] wgt = { 10, 20, 30, 40, 50 };
int[] val = { 50, 120, 150, 210, 240 };
int cap = 50;
// Жадный алгоритм
double res = fractionalKnapsack(wgt, val, cap);
System.out.println("Максимальная стоимость предметов без превышения вместимости рюкзака = " + res);
}
}