题解:SP130 RENT - Rent your airplane and make money

· · 题解

题目大意

给定 n 个任务。对于每一个任务都有初始时间 l_i、终止时间 r_i 和价值 val_i。选择一组任务使得任务的时间区间不重合,求这组任务价值的最大值。

思路

对于这样的一类问题,可以使用动态规划解决。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;

const int N = 1e5+5;
struct node {
    int l, r, val;
    bool operator<(const node other)const {
        return r < other.r;
    }
} a[N];
int T, n, dp[N];

signed main() {
    cin.tie(0), cout.tie(0);
    cin >> T;
    while (T--) {
        cin >> n;
        for (int i = 1; i <= n; i++)    cin >> a[i].l >> a[i].r >> a[i].val;
        for (int i = 1; i <= n; i++)    a[i].r += a[i].l;
        sort(a + 1, a + 1 + n);

        dp[0] = 0;  // 多组问题不要忘记初始化,警钟敲烂
        for (int i = 1; i <= n; i++) {
            int x = lower_bound(a + 1, a + i, (node) { 114, a[i].l, 514 }) - a - 1;
            dp[i] = max(dp[i - 1], dp[x] + a[i].val);
        }
        cout << dp[n] << "\n";
    }
    return 0;
}