微众某道笔试题。。贪心算法。排个序就行
public class Main{public static void main(String[] args){Scanner sc = new Scanner(System.in);while(sc.hasNext()){int cards = sc.nextInt(); //卡片总数ArrayList<Entry> list = new ArrayList<>();for(int i = 0; i < cards; i++){int money = sc.nextInt();int exChance = sc.nextInt();Entry e = new Entry(money, exChance);list.add(e);}//排序思路:贪心。把卡片上额外次数最多的卡片防在最前面,如果额外次数一样多,那么金额大的放在前面。Collections.sort(list, (e1, e2) ->e1.exChance != e2.exChance ? (e2.exChance - e1.exChance) : (e2.money - e1.money));int res = 0;int chances = 1;for(int i = 0; i < cards; i++){chances --;res += list.get(i).money;chances += list.get(i).exChance;if(chances == 0)break;}System.out.println(res);}}public static class Entry{int money ;int exChance;public Entry(int money, int exChance){this.money = money;this.exChance = exChance;}}
}