【CodeForces

来源:互联网 发布:诛仙手游破凶辅助软件 编辑:程序博客网 时间:2024/06/05 19:37

E - Hanoi Factory


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 jon 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 aibi and hi (1 ≤ ai, bi, hi ≤ 109bi > 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.

Example
Input
31 5 12 6 23 7 3
Output
6
Input
41 2 11 3 34 6 25 7 1
Output
4
Note

In the first sample, the optimal solution is to take all the rings and put them on each other in order 321.

In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4.


题意:给你n个圆环,内径为l,外径为r,高度为h,问这些圆环堆叠的最大高度是多少。堆叠的条件是上层圆环的外径<=下层圆环的外径且>下层圆环的内径。


分析:很容易想到按外径的大小排序贪心。但是这里的排序要注意一下,当两圆环的外径相同时,内径要按照从大到小的顺序排序,因为我们要尽可能地使得上层容易满足条件。栈这种数据结构对于这道题非常适用(FIFO先进先出),满足条件继续堆叠,否则取出最上的一个。


代码如下:

#include <map>#include <cmath>#include <queue>#include <stack>#include <vector>#include <cstdio>#include <string>#include <cstring>#include <iostream>#include <algorithm>#define LL long long#define INF 0x3f3f3f3fusing namespace std;const int MX = 1e5 + 5;struct node{    LL l, r, h;}ring[MX];bool cmp(node a, node b){    if(a.r == b.r && a.l == b.l)    return a.h > b.h;    if(a.r == b.r)  return a.l > b.l;    return a.r > b.r;}stack<node> s;int main(){    int n;    scanf("%d", &n);    for(int i = 0; i < n; i++){        cin >> ring[i].l >> ring[i].r >> ring[i].h;    }    sort(ring, ring + n, cmp);    LL ans = 0, sum = 0;    for(int i = 0; i < n; i++){        while(!s.empty()){            node tmp;            tmp = s.top();            if(tmp.l < ring[i].r)   break;            sum -= tmp.h;            s.pop();        }        s.push(ring[i]);        sum += ring[i].h;        ans = max(ans, sum);    }    cout << ans << endl;    return 0;}