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.
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.
Print one integer — the maximum height of the tower that can be obtained.
3 1 5 1 2 6 2 3 7 3
6
4 1 2 1 1 3 3 4 6 2 5 7 1
4
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
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个环的内径和外径和高,一个环可以叠到另一个环的条件是bi<=bj bi>aj,问能叠到的最高高度。
题解:排个序贪心,排序的方法是b大的放前面,如果相同则a大的放前面。
这样排序是因为外径最大肯定要放最下面,当b相同时,那么a小的可以放到a大的上面且能尽量满足下一个b能大于a。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
struct node{
ll a,b,h;
bool operator<(const node& c) const {
if(b==c.b)return a>c.a;
return b>c.b;
}
}e[100050],stack[100050];
ll n,top;
ll now=0,ans=0;
int main(){
ll i;
cin>>n;
for(i=1;i<=n;i++)scanf("%lld%lld%lld",&e[i].a,&e[i].b,&e[i].h);
sort(e+1,e+1+n);
for(i=1;i<=n;i++){
while(top&&e[i].b<=stack[top-1].a) {
now-=stack[top-1].h;
top--;
}
stack[top++]=e[i];
now+=e[i].h;
ans=max(ans,now);
}
cout<<ans<<endl;
return 0;
}