题目描述
题目描述:
抽卡是一类类似于博弈的游戏。现在有一种抽卡方式,描述如下:
初始你只有一次抽卡机会。每次抽卡浪费一次抽卡机会,获得一张卡片。这张卡片上有两个数字,第一个数字代表你能获得的钱,第二个数字代表你能获得的额外抽卡次数。额外的抽卡次数是可以累计的。
现在,你知道了卡片的数量,所有的卡片上的数字,以及所有卡片的顺序。你只需要安排一种抽卡顺序,使得你能获得钱数最多。
输入
第一个行一个数n,代表卡片的数量。 接下来n行,每行用两个数ai,bi描述一张卡片。ai表示抽这张卡能获得的钱数,bi表示抽这张卡能获得的额外抽卡次数。
输出
一行一个数,代表你能获得的最多钱数。
样例输入
5
0 2
1 1
1 0
1 0
2 0
样例输出
4
提示
对于100%的数据,0≤a_i,b_i≤1000,1≤n≤1000
样例解释:按顺序抽第2,1,5,4张卡
网友参考代码
作者:Galliano、
链接:https://www.nowcoder.com/discuss/403152?type=all&order=time&pos=&page=1
来源:牛客网
/**
* 微众 第 3 题,最大利益问题
*/
public static void main3(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
int[][] mat = new int[n][2];
for (int i = 0; i < n; i++) {
String[] strings = sc.nextLine().split(" ");
mat[i][0] = Integer.parseInt(strings[0]);
mat[i][1] = Integer.parseInt(strings[1]);
}
sc.close();
System.out.println(mostMoney(mat));
}
private static int mostMoney(int[][] mat) {
if (mat.length == 0) return 0;
// 使用一个最大堆,排序规则为:
// 先比较卡片的额外抽卡次数, 额外抽卡次数最多的卡片 的优先级较高
// 当 卡片的额外抽卡次数 相同时,再比较该卡能获得的钱数,能获得的钱数最多的卡片 的优先级较高
PriorityQueue<Pair> heap =
new PriorityQueue<>((Pair p1, Pair p2) ->
(p1.num.equals(p2.num)) ? p2.money.compareTo(p1.money) : p2.num.compareTo(p1.num));
for (int[] arr : mat) heap.add(new Pair(arr[0], arr[1]));
int count = 1, res = 0;
while (!heap.isEmpty() && count > 0) {
count--;
Pair poll = heap.poll();
res += poll.money;
count += poll.num;
}
return res;
}
public static class Pair {
Integer money;
Integer num;
public Pair(Integer money, Integer num) {
this.money = money;
this.num = num;
}
}
【Java】 用PriorityQueue实现最大最小堆
https://www.cnblogs.com/yongh/p/9945539.html