洛谷——P2676 [USACO07DEC] Bookshelf B

Posted on 2024-03-17 21:13  奇诺qwq  阅读(22)  评论(0编辑  收藏  举报

 

 

思路:(贪心&排序)

1、升序排序数组,优先选择身高max的奶牛

2、选择一只奶牛的同时,用ans记录数量

 

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

public class Main {
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        int n = sc.nextInt();
        long B = sc.nextInt();
        long[] arr = new long[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        Arrays.sort(arr);
        long S = 0;//总身高
        int j=n-1,ans=0;
        while(S<B&&j>0){//j从大到小
            S+=arr[j--];
            ans++;
        }
        System.out.println(ans);
    }
}