示例1
输入:
3
1 9
2 1
4 1
输出:
11
示例二
输入:
6
4 2
8 4
3 0
2 3
7 1
0 1
输出:
13
思路:
重现的时候没过,之后看了过题的代码才明白。这题首先要求所有山都要经过然后回到出发点,也就意味着所有梯子都是要被用到的,往高的山走如果梯子不够长就要做飞机,这个是额外花费。既然所有梯子都要被用到,那么就在输入的时候就可以先把花费记起来,然后用贪心的思想,如何避免额外的花费呢,那就是每次都尽量往能到的最高的山上去,但是这样不容易维护,换一种思路,把数组按高度sort一遍,然后从左到右遍历,维护一个最大值,如果当前最大值都到不了这座山,那就把费用加上,然后更新高度,遍历完就能得到最后的答案。
代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline void IO_STREAM() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
const int MAXN = 1e5 + 5e2;
int n;
struct Node {
int h, x;
friend bool operator<(const Node &a, const Node &b) {
if (a.h != b.h) {
return a.h < b.h;
}
return a.x < b.x;
}
} mon[MAXN];
int main() {
IO_STREAM();
cin >> n;
ll cost = 0;
for (int i = 0; i < n; i++) {
cin >> mon[i].h >> mon[i].x;
cost += mon[i].x;
}
sort(mon, mon + n);
int last = mon[0].h + mon[0].x;
for (int i = 1; i < n; i++) {
if (mon[i].h > last) {
cost += mon[i].h - last;
}
last = last > mon[i].h + mon[i].x ? last : mon[i].h + mon[i].x;
}
cout << cost << endl;
return 0;
}