题目大意:
现在一共有N个零件,如果存在:bi>=bj&&bj>ai的两个零件i,j,那么此时我们就可以将零件j放在零件i上。我们现在要组成一个大零件,使得高度最高,问这个最高高度。
思路:看了题解,先将木块按b从大到小排序,相同的再按a从大到小排序。(这样排序后满足两点性质,第一,如果第i块不能放在已经放好的木台上,说明此时的b小于木台最上面的a,而这个序列后续所有的b都比当前的b小,也就是后面所有的木块都不能放在现在的木台上,要想继续放,必须把当前木块最上面那块拿出来)。这样就满足了先进后出的原则,用栈来模拟,用sum表示当前木台的高度,ans表示历史最大的高度。比一下就好了。
代码。
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<bitset>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#define CLR(x,y) memset(x,y,sizeof(x))
#define LC(x) (x<<1)
#define RC(x) ((x<<1)+1)
#define MID(x,y) ((x+y)>>1)
using namespace std;
typedef long long ll;
const int maxn=100010;
struct dian{
ll a,b,h;
}s[maxn];
int n;
bool cmp(dian x,dian y){//相同的b 应该把a小一点的放上面
if(x.b-y.b)return x.b>y.b;
return x.a>y.a;
}
int main(){
cin>>n;
for(int 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);
stack<dian>q;
ll ans,sum;
ans=sum=s[1].h;
q.push(s[1]);
for(int i=2;i<=n;i++){
while(!q.empty()&&s[i].b<=q.top().a){//如果不能放在当前的这个上面,说明此时的b小于下面的a,那后面的所有b肯定都会小于下面的a
sum-=q.top().h; //所以如果想继续放 就必须把下面那一块拿出来
q.pop();
}
sum+=s[i].h;
q.push(s[i]);
ans=max(ans,sum);
}
cout<<ans<<endl;
}
1 second
256 megabytes
standard input
standard output
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.