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 ifbj ≤ bi.
- Rings should not fall one into the the other. That means one can place ring j on the ring i only ifbj > 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 1on the ring 2 and get the tower of height 4.
题意:汉诺塔大家都听过,现在有n个空心圆盘,每个内径a,外径b,高度c。求最高能垒多高,条件:上一层的外径必须要大于下一层的内径且小于等于下一层的外径。
思路:对于这个题我们大家可能一下子就想到了贪心,没错就是一个贪心.
我们对这些圆盘先按照b从大到小排序,如果b相同,那么就要按照a从大到小排序,这是为什么呢?
这是因为如果有b相同的我们要优先使用那个a大的,因为你想越往上b越小,你要想让b>a的话那么就要让a也小,这样才能让h更大一些
另外 对于这个题我们可以知道 垒圆盘问题像一个栈 后进先出 所以我们在将所有的圆盘压入栈中然后记录一下最大值即可.
而且这样也可以保证如果当前的圆盘不能继续往上垒了那么剩下的一定也不可以了
具体见代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e5+10;
struct node
{
int a,b,h;
}q[maxn];
int cmp(node x,node y)
{
if(x.b==y.b)
return x.a>y.a;
else
return x.b>y.b;
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&q[i].a,&q[i].b,&q[i].h);
}
sort(q,q+n,cmp);
stack<node>s;
while(!s.empty())
{
s.pop();
}
s.push(q[0]);
ll sum=q[0].h,ans=q[0].h;
for(int i=1;i<n;i++)
{
while(!s.empty()&&q[i].b<=s.top().a)
{
sum-=s.top().h;
s.pop();
}
sum+=q[i].h;
ans=max(ans,sum);//更新最值
s.push(q[i]);
}
printf("%I64d\n",ans);
return 0;
}

探讨如何通过贪心算法解决汉诺塔圆环堆叠问题,目标是在遵循特定规则的情况下实现圆环堆叠的最大高度。
1060

被折叠的 条评论
为什么被折叠?



