Description
There are n irony ring in a factory. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of irony ring to create as high town as possible . The subset of irony ring following condition are satisifed:- 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;
- the above ring’s outer radius should longer than the below ring’s inner radius. That means one can place ring j on the ring i only if bj>ai.
- The total height of ring used should be maximum possible.
Input
The first line contain a integer n ( 1<=n<=100000 )--the number of irony ring in the factory. The i-th line of the next n lines contains three integers ai, bi, hi ( 1<=ai, bi, hi<=10^ 9, ai<bi )--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.
Sample Input
3 1 5 1 2 6 2 3 7 3 4 1 2 1 1 3 3 4 6 2 5 7 1
Sample Output
6 4
Hint
In the first sample, the optimal solution is to take all the ring and put them on each other in order 3 2 1 In the second sample, one can put 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.
Source
Author
王树帆
其实,贪心算法也是博大精深的,不要以为他很简单,很多时候要考虑的东西还是很多的。具体代码如下:
#include<bits/stdc++.h>
using namespace std;
struct Ring
{
int in,ot,h;
} r[101000];
bool operator <(const Ring a,const Ring b)
{
return a.ot==b.ot?a.in>b.in:a.ot>b.ot;
}
int main()
{
int n;
while (~scanf("%d",&n))
{
for(int i=1;i<=n;i++)
scanf("%d%d%d",&r[i].in,&r[i].ot,&r[i].h);
sort(r+1,r+n+1);
stack<Ring> sta;
sta.push(r[1]);
long long ans=r[1].h,h=r[1].h;
for(int i=2;i<=n;i++)
{
while (!sta.empty()&&sta.top().in>=r[i].ot)
{
h-=sta.top().h; sta.pop();
}
sta.push(r[i]);
h+=r[i].h;
ans=max(ans,h);
}
printf("%lld\n",ans);
}
return 0;
}