zoukankan      html  css  js  c++  java
  • Trapping Rain Water

    使用栈结构解决。

    #include <iostream>
    #include <stack>
    using namespace std;
    
    class Solution {
    public:
        int trap(int A[], int n) {
    if (n<3){ return 0; }
    stack
    <int> water_stack; int begin=0; int res=0;
    for (int i =0;i<n;++i){ if (A[i]>0 && water_stack.empty()){ water_stack.push(A[i]); begin=A[i]; continue; } if (A[i]<begin){ water_stack.push(A[i]); continue; } if (A[i]>=begin && begin!=0){ while(!water_stack.empty()){ //cout<<"A"<<i<<": "<<A[i]; //cout<<" begin: "<<begin; //cout<<" top: "<<water_stack.top()<<endl; res+=begin-water_stack.top(); water_stack.pop(); } water_stack.push(A[i]); begin=A[i]; } //cout<<"res: "<<res<<endl; }
    int end=0; while(!water_stack.empty()){ if(water_stack.top()>=end){ end=water_stack.top(); water_stack.pop(); } else{ res+=end-water_stack.top(); water_stack.pop(); } }
    return res; } }; int main(int argc, char** argv) { Solution s; int A[]={0,1,0,2,1,0,1,3,2,1,2,1}; cout<<s.trap(A,12); return 0; }

     写的并不完美,看起来是为了用栈而用栈,其实不用栈也能解决。

  • 相关阅读:
    loj6158 A+B Problem (扩展KMP)
    2017CodeM初赛B场
    Codeforces Round #421(div 2)
    CF821E(多次矩阵快速幂)
    Codechef-ANCESTOR(树套树/CDQ分治)
    Codechef-BLACKCOM(树形背包dp)
    Codechef-CHEFPRAD(找事件点+贪心)
    洛谷 p3391
    luogu p3369
    LOJ10082
  • 原文地址:https://www.cnblogs.com/iois/p/4058901.html
Copyright © 2011-2022 走看看