zoukankan      html  css  js  c++  java
  • Java实现蓝桥杯 算法提高 盾神与积木游戏

    题目描述
    最近的m天盾神都去幼儿园陪小朋友们玩去了~
    每个小朋友都拿到了一些积木,他们各自需要不同数量的积木来拼一些他们想要的东西。但是有的小朋友拿得多,有的小朋友拿得少,有些小朋友需要拿到其他 小朋友的积木才能完成他的大作。如果某个小朋友完成了他的作品,那么他就会把自己的作品推倒,而无私地把他的所有积木都奉献出来;但是,如果他还没有完成 自己的作品,他是不会把积木让出去的哟~
    盾神看到这么和谐的小朋友们感到非常开心,于是想帮助他们所有人都完成他们各自的作品。盾神现在在想,这个理想有没有可能实现呢?于是把这个问题交给了他最信赖的你。

    数据规模和约定
    1< =n< =10000,1< =m< =10。

    输入
    第一行为一个数m。
    接下来有m组数据。每一组的第一行为n,表示这天有n个小朋友。接下来的n行每行两个数,分别表示他现在拥有的积木数和他一共需要的积木数。
    输出
    输出m行,如果第i天能顺利完成所有作品,输出YES,否则输出NO。
    样例输入
    2
    2
    2 2
    1 3
    3
    1 5
    3 3
    0 4
    样例输出
    YES
    NO
    贪心算法(银行家算法的可行性,考虑到要求的不同)

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Arrays;
    
    public class Main {
    
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            int m = Integer.parseInt(bufferedReader.readLine());
            for (int i = 0; i < m; i++) {
                int n = Integer.parseInt(bufferedReader.readLine());
                Child[] childs = new Child[n];
                for (int j = 0; j < n; j++) {
                    String[] t = bufferedReader.readLine().split(" ");
                    childs[j] = new Child(Integer.parseInt(t[0]), Integer.parseInt(t[1]));
                }
    
                System.out.println(bankAlgorithm(childs));
            }
            bufferedReader.close();
        }
    
        private static String bankAlgorithm(Child[] childs) {
            Arrays.sort(childs);
            int currentNeed = 0;
            for (int i = 0; i < childs.length; i++) {
                if (childs[i].need <= 0) {
                    currentNeed += childs[i].have;
                } else { // childs[i].need > 0
                    if (currentNeed >= childs[i].need) {
                        currentNeed += childs[i].have;
                    } else {
                        return "NO";
                    }
                }
            }
            return "YES";
        }
    }
    
    class Child implements Comparable<Child> {
        int have;
        int total;
        int need;
    
        public Child(int have, int total) {
            this.have = have;
            this.total = total;
            this.need = total - have;
        }
    
        
        public int compareTo(Child child) {
            return need - child.need;
        }
    
    }
    
  • 相关阅读:
    Maven 环境的配置
    zTree的简单例子
    plsql免安装客户端的配置
    HDU 1232 畅通工程
    HDU 5698 瞬间移动
    Codeforces 1015E1 Stars Drawing (Easy Edition)
    Codeforces 784B Santa Claus and Keyboard Check
    Codeforces 500C New Year Book Reading
    NSarray 赋值 拷贝 等问题记录
    UINavigationController 操作记录
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13079488.html
Copyright © 2011-2022 走看看