题解:P16789 [蓝桥杯 2026 国 A] 核心任务调度

· · 题解

P16789

题意就不多说了,反悔贪心板子题,如果不熟悉反悔贪心的话可以看看这道题(虽然是道青题吧)。

思路

因为是反悔贪心,考虑使用堆,但又不太一样,这道题分了一个普通任务和一个核心任务,所以使用两个小根堆(因为要尽量的把时间紧迫的任务做完),一个 q_1,用来维护普通任务;另一个 q_2,用来维护核心任务。到最后如果时间不够但有价值更高的任务的话则使用反悔贪心,并且核心任务的优先级要高于普通任务,所以到时候弹出的话优先弹出普通任务,如果没有普通任务再弹出核心任务,并且可以发现,丢弃的普通任务并不会影响核心任务的数量,所以优先丢弃价值最小的任务。 ::::success[代码]

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5+5;
int n, t;//t是当前累计时间,ans是最大价值
int ans;
priority_queue<int, vector<int>, greater<int>> q1, q2;
struct node
{
    int t, w, is_key;
} a[N];
int32_t main()
{
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++)
        scanf("%lld %lld %lld", &a[i].t, &a[i].w, &a[i].is_key);
    sort(a + 1, a + 1 + n, [](node x, node y)//按照时间从小(紧急)到大(宽松)排序
    {
        return x.t < y.t;
    });
    for (int i = 1; i <= n; i++)
    {
        ans += a[i].w;
        if (!a[i].is_key)
            q1.push(a[i].w);
        else
            q2.push(a[i].w);
        t++;
        if (t > a[i].t)//反贪板子
        {
            t--;
            if (!q1.empty())
                ans -= q1.top(), q1.pop();//优先弹出普通任务
            else
                ans -= q2.top(), q2.pop();
        }
    }
    printf("%lld %lld", q2.size(), ans);
    return 0;
}

::::