程式儲存問題

來源:互聯網
上載者:User

標籤:程式儲存問題   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;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.