解题思路:
根据需要积木的数量与持有积木的数量的差值进行排序,小的在前面。这样释放的公共积木越多,sum来存公共的积木数,count 来统计完成积木搭建的小朋友数量,如果等于n则代表全部完成。
注意事项:
参考代码:
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc =new Scanner(System.in); int m = sc.nextInt(); int n = 0; Jm[] jm ; while(m -- >0){ n = sc.nextInt(); jm = new Jm[n]; for (int i = 0; i < jm.length; i++) { jm[i] = new Jm(sc.nextInt(),sc.nextInt()); } Arrays.sort(jm); int sum = 0; int count = 0; for (Jm j : jm) { if(j.n == j.y){ // 持有与需要相同,则直接释放积木 sum += j.y; count++; }else{ if(j.n-j.y <= sum){ //需要的积木 小于等于 公共积木数量 sum -= j.n-j.y; // 搭建完成 所需的积木 sum+=j.n;// 再释放积木 count++; }else{ System.out.println("NO"); // 如果大于 代表后面都不满足了,直接输出NO,结束本组 break; } } } if(count == n) System.out.println("YES"); } } } class Jm implements Comparable<Jm>{ public int y; public int n; public Jm(int y, int n) { super(); this.y = y; this.n = n; } @Override public String toString() { return "Jm [y=" + y + ", n=" + n + "]"; } @Override public int compareTo(Jm o) { int n1 = this.n - this.y; int n2 = o.n - o.y; return n1-n2; } }
0.0分
1 人评分