有N个任务需要执行,第i个任务计算时占R[i]个空间,而后会释放一部分,最后储存计算结果需要占据O[i]个空间(O[i] < R[i])。
例如:执行需要5个空间,最后储存需要2个空间。给出N个任务执行和存储所需的空间,问执行所有任务最少需要多少空间。
输入
第1行:1个数N,表示任务的数量。(2 <= N <= 100000)
第2 - N + 1行:每行2个数R[i]和O[i],分别为执行所需的空间和存储所需的空间。(1 <= O[i] < R[i] <= 10000)
输出
输出执行所有任务所需要的最少空间。
输入示例
20
14 1
2 1
11 3
20 4
7 5
6 5
20 7
19 8
9 4
20 10
18 11
12 6
13 12
14 9
15 2
16 15
17 15
19 13
20 2
20 1
输出示例
135
此题的贪心策略比较奇特:每次先选当前R[i]-O[i] 最小的进行操作
#include <cstdio>
#include <cstring>
#include <functional>
#include <algorithm>
#include <cctype>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
vector<P> v;
int main() {
//freopen("in.txt", "r", stdin);
int n;
scanf("%d", &n);
for (int i = 0, r, o; i < n; ++i) {
scanf("%d%d", &r, &o);
v.push_back(P(r-o, o));
}
sort(v.begin(), v.end(), less<P>() );
ll total = 0, used = 0, empty = 0;
for (int i = 0, r, o; i < n; ++i) {
r = v[i].first + v[i].second;
o = v[i].second;
used += 0;
if (r > empty) {
if (r - empty > o) {
total += r - empty;
} else {
total += o;
}
} else {
total += o;
}
empty = total - used;
}
printf("%lld\n", total);
return 0;
}