普及练习场 贪心EX 皇后游戏

本文通过一次大臣排序问题,介绍了如何使用Java实现一种特定的排序算法,并通过动态规划求解最优解的过程。文章详细展示了代码实现,包括自定义类、比较器及快速输入输出等技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

题意理解

显然,第 i+1 位大臣拿的钱比第 i 位大臣多

i1位大臣拿的钱为 ci1 ,第 i 位大臣和第i+1位大臣拿的钱可以分别表示出来。此时顺序是, i1,i,i+1

然后交换第 i 位大臣和第i+1位大臣。此时顺序是 i1,i+1,i

此时我们希望第 i+1 位大臣排在后面拿的钱要少与第 i 位大臣排在后面的前,此时就有不等式了

代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
class People implements Comparable{
    int l;
    int r;
    public People(int l, int r) {
        this.l = l;
        this.r = r;
    }
    @Override
    public int compareTo(Object o) {
        People people = (People)o;
        return Math.min(this.l, people.r) - Math.min(this.r, people.l);
    }

}
public class Main {
    static int T;
    static int n;
    static People[] peoples;
    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        T = fs.nextInt();
        while(T-->0) {
            long sum = 0;
            long[] dp = new long[50050];
            dp[0] = 0;
            n = fs.nextInt();
            peoples = new People[n];
            for(int i = 0; i < n; i++) {
                int x = fs.nextInt();
                int y = fs.nextInt();
                peoples[i] = new People(x, y);
            }
            Arrays.sort(peoples);
            for(int i = 0; i < n; i++) {
                sum += peoples[i].l;
                dp[i] = Math.max(dp[Math.max(0, i - 1)], sum) + peoples[i].r;
            }
            System.out.println(dp[n-1]);
        }
    }
    public static class FastScanner {
        private BufferedReader br;
        private StringTokenizer st;

        public FastScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public String nextToken() {
            while(st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.valueOf(nextToken());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值