【CodeForces - 777E Hanoi Factory】 貪心+棧

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
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 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 0x3f3f3f3f
using 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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章