Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:
Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj ≤ bi.
Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.
The total height of all rings used should be maximum possible.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of rings in factory's stock.
The i-th of the next n lines contains three integers ai, bi and hi (1 ≤ ai, bi, hi ≤ 109, bi > ai) — inner radius, outer radius and the height of the i-th ring respectively.
Output
Print one integer — the maximum height of the tower that can be obtained.
使用贪心算法,b按从大到小排序,b相同的情况下,a按从大到小排序,然后来个栈模拟一下,动态记录更新最大值。
AC代码:
#include<stdio.h>
#include<iostream>
#include<vector>
#include<stack>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<map>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
int n;
struct node {
int a, b, h;
};
node s[100010];
int cmp(node a, node b) {
if (a.b != b.b) {
return a.b > b.b;
}
else {
return a.a > b.a;
}
}
stack<node> p;
int judge(node a, node b) {
if (a.b >= b.b&a.a < b.b) {
return 1;
}
return 0;
}
int main() {
int i, j, k;
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%d%d%d", &s[i].a, &s[i].b, &s[i].h);
}
sort(s + 1, s + 1 + n, cmp);
while (!p.empty()) {
p.pop();
}
ll ans=s[1].h, sum=s[1].h;
p.push(s[1]);
for (i = 2; i <= n; ) {
if (p.empty()) {
sum = sum + s[i].h;
p.push(s[i]);
if (sum > ans) {
ans = sum;
}
i++;
continue;
}
if (judge(p.top(), s[i])) {
sum = sum + s[i].h;
p.push(s[i]);
i++;
if (sum > ans) {
ans = sum;
}
}
else {
sum = sum - p.top().h;
p.pop();
}
}
printf("%I64d", ans);
return 0;
}