標籤:程式儲存問題 java 演算法
程式儲存問題
題目:設有 n 個程式 { 1 , 2 , 3 , … , n } 要存放在長度為 L 的磁帶上。程式i存放在磁帶上的長度是 li , 1 ≤ i ≤ n 。要求確定這 n 個程式在磁帶上的一個儲存方案,使得能夠在磁帶上儲存儘可能多的程式。
輸入資料中,第一行是 2 個正整數,分別表示程式檔案個數和磁帶長度L。接下來的 1 行中,有 n 個正整數,表示程式存放在磁帶上的長度。
輸出為最多可以儲存的程式個數。
輸入資料樣本
6 50
2 3 13 8 80 20
輸出資料
5
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()) {int n = scanner.nextInt();int l = scanner.nextInt();int[] nums = new int[n];for (int i = 0; i < n; i++) {nums[i] = scanner.nextInt();}sort(nums, 0, n - 1);// 排序int count = 0, sum = 0;for (int i = 0; i < n; i++) {sum += nums[i];if (sum > l) {break;} else {count++;}}System.out.println(count);}scanner.close();}// 快排private static void sort(int[] nums, int start, int end) {if (start >= end) {return;}int key = nums[start];int i = start + 1;int j = end;while (true) {while (i <= end && nums[i] < key) {i++;}while (j > start && nums[j] > key) {j--;}if (i < j) {swap(nums, i, j);} else {break;}}// 交換j和分界點的值swap(nums, start, j);// 遞迴sort(nums, start, j - 1);sort(nums, j + 1, end);}// 資料交換private static void swap(int[] nums, int i, int j) {int temp = nums[i];nums[i] = nums[j];nums[j] = temp;}}