[CF777E] Hanoi Factory(贪心,栈)

题目链接:http://codeforces.com/problemset/problem/777/E

外环从大到小,内环从大到小排序。用一个栈来存当前待选择做底盘的环。遍历每一个环,找到第一个内环符合条件的栈中环,更新当前遍历到的环的高度,放入栈。更新答案即可。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef long long LL;
 5 typedef struct P {
 6     LL a, b, h;
 7     P() {}
 8     P(LL a, LL b, LL h) : a(a), b(b), h(h) {}
 9 }P;
10 const LL maxn = 100100;
11 LL n;
12 P p[maxn];
13 
14 bool cmp(P x, P y) {
15     if(x.b == y.b) return x.a > y.a;
16     return x.b > y.b;
17 }
18 stack<P> st;
19 
20 signed main() {
21     // freopen("in", "r", stdin);
22     while(~scanf("%I64d", &n)) {
23         for(LL i = 1; i <= n; i++) {
24             scanf("%I64d%I64d%I64d",&p[i].a,&p[i].b,&p[i].h);
25         }
26         sort(p+1, p+n+1, cmp);
27         while(!st.empty()) st.pop();
28         LL ret = 0;
29         for(LL i = 1; i <= n; i++) {
30             while(!st.empty() && p[i].b <= st.top().a) st.pop();
31             if(!st.empty()) p[i].h += st.top().h;
32             st.push(p[i]);
33             ret = max(ret, st.top().h);
34         }
35         printf("%I64d
", ret);
36     }
37     return 0;
38 }
原文地址:https://www.cnblogs.com/kirai/p/7257356.html