Pemrograman KompetitifMudah

Ransel Pecahan

Panduan terperinci dan implementasi Python untuk masalah 'Fractional Knapsack'.

Pernyataan Masalah

Mudah

Tulis fungsi fractional_knapsack(W, items) yang mengambil kapasitas knapsack W dan daftar tupel items di mana setiap tupel adalah (value, weight). Temukan nilai total maksimum yang dapat diperoleh di ransel, yang memungkinkan item dipecah/dipecah. Bulatkan hasilnya menjadi 2 tempat desimal.

Kendala
  • 1 <= len(items) <= 1000
  • 1 <= W <= 10^5
  • 1 <= value, weight <= 10^4

Contoh

Example 1
Input
fractional_knapsack(50, [(60, 10), (100, 20), (120, 30)])
Output
240.0
Explanation

Take the first and second item fully, and 2/3 of the third item. Total value: 60 + 100 + 120 * (20/30) = 240.0.

Example 2
Input
fractional_knapsack(15, [(24, 10), (18, 10), (15, 10)])
Output
33.0
Explanation

Take the first item fully, and 1/2 of the second item. Total value: 24 + 18 * 0.5 = 33.0.

Need a Hint?
Pertimbangkan untuk menggunakan struktur data khusus Greedy seperti kumpulan atau tumpukan.
Edge Cases to Watch
  • Struktur masukan kosong
  • Masukan elemen tunggal
  • Batasan angka yang besar

Siap Memecahkannya?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Buka di Editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Sumber Daya Python yang Direkomendasikan

Perluas pengetahuan Anda dengan tutorial interaktif terkait, lembar contekan, dan perbandingan kode.