一、题目
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、原题链接
二、解题报告
1、思路分析
很好理解的贪心
就以生活中的各种deadline而言,我们一般愿意把deadline晚的放到后面做,先做deadline早的
当然,事情也分重要程度,如果deadline早的一堆事情的重要程度比不上deadline晚的那一件事情,我们自然也会放弃前面的事情
那么本题就可以做了
- 按照deadline升序排序,deadline相同的按照分数降序排序
- 遍历数组,开一个小根堆,保存的是已经选择要完成的deadline的分数
- 如果当前遍历的deadline无法完成,我们将其分数和堆顶比较,如果它更大,我们就放弃堆顶的deadline,加上它的代价,弹出,将当前枚举到的deadline的分数压入堆顶
- 如果可以完成,直接入堆即可
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;
}