算法设计与分析: 4-5 程序存储问题

4-5 程序存储问题


问题描述

设有 n 个程序{1,2,…, n }要存放在长度为 L 的磁带上。程序 i 存放在磁带上的长度是 l i 1 i n
程序存储问题要求确定这 n 个程序在磁带上的一个存储方案,使得能够在磁带上存储尽可能多的程序。

对于给定的 n 个程序存放在磁带上的长度,编程计算磁带上最多可以存储的程序数。

数据输入:
第一行是 2 个正整数,分别表示文件个数 n 和磁带的长度 L。接下来的 1 行中,有 n 个正整数,表示程序存放在磁带上的长度。


Java

import java.util.Arrays;
import java.util.Scanner;

public class ChengXuCunChu {

    private static int n,m;
    private static int[] len;

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);

        while (true){
            n = input.nextInt();
            m = input.nextInt();

            len = new int[n];

            for(int i=0; i<n; i++)
                len[i] = input.nextInt();

            Arrays.sort(len);

            int result = greedy();

            System.out.println(result);
        }
    }

    private static int greedy(){
        int i=0,sum=0;
        while(i < n){
            sum += len[i];
            if(sum <= m)
                i++;
            else
                return i;
        }

        return n;
    }
}

Input & Output

6  50
2 3 13 8 80 20
5

王晓东《计算机算法设计与分析》(第3版)P130

猜你喜欢

转载自blog.csdn.net/ioio_/article/details/81058018
4-5
今日推荐