贪心+堆维护,HDU1789Doing Homework again

一、题目

1、题目描述

Ignatius has just come back school from the 30th ACM/ICPC. Now he has a lot of homework to do. Every teacher gives him a deadline of handing in the homework. If Ignatius hands in the homework after the deadline, the teacher will reduce his score of the final test. And now we assume that doing everyone homework always takes one day. So Ignatius wants you to help him to arrange the order of doing homework to minimize the reduced score.

2、输入输出

2.1输入

The input contains several test cases. The first line of the input is a single integer T that is the number of test cases. T test cases follow.
Each test case start with a positive integer N(1<=N<=1000) which indicate the number of homework.. Then 2 lines follow. The first line contains N integers that indicate the deadlines of the subjects, and the next line contains N integers that indicate the reduced scores.

2.2输出

For each test case, you should output the smallest total reduced score, one line per test case.

3、原题链接

Problem - 1789 (hdu.edu.cn)


二、解题报告

1、思路分析

很好理解的贪心

就以生活中的各种deadline而言,我们一般愿意把deadline晚的放到后面做,先做deadline早的

当然,事情也分重要程度,如果deadline早的一堆事情的重要程度比不上deadline晚的那一件事情,我们自然也会放弃前面的事情

那么本题就可以做了

  1. 按照deadline升序排序,deadline相同的按照分数降序排序
  2. 遍历数组,开一个小根堆,保存的是已经选择要完成的deadline的分数
  3. 如果当前遍历的deadline无法完成,我们将其分数和堆顶比较,如果它更大,我们就放弃堆顶的deadline,加上它的代价,弹出,将当前枚举到的deadline的分数压入堆顶
  4. 如果可以完成,直接入堆即可

2、复杂度

时间复杂度: O(nlogn)空间复杂度:O(n)

3、代码详解

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 1e6 + 10, inf = 0x3f3f3f3f;
int n;
PII a[N];
void solve()
{
    cin >> n;
    int ans = 0;
    for (int i = 0; i < n; i++)
        cin >> a[i].first;
    for (int i = 0; i < n; i++)
        cin >> a[i].second, a[i].second *= -1;
    sort(a, a + n);
    priority_queue<int, vector<int>, greater<int>> pq;
    for (int i = 0; i < n; i++)
    {
        if (a[i].first > pq.size())
            pq.emplace(-a[i].second);
        else
        {
            if (-a[i].second > pq.top())
                ans += pq.top(), pq.pop(), pq.emplace(-a[i].second);
            else
                ans -= a[i].second;
        }
    }
    cout << ans << '\n';
}
int main()
{
    //freopen("in.txt", "r", stdin);
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int _ = 1;
    cin >> _;
    while (_--)
    {
        solve();
    }
    return 0;
}

  • 21
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EQUINOX1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值