LeetCode-Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

用一个栈辅助,小于等于栈顶的话压入,大于栈顶就把所有小于当前值的元素出栈,计算面积

面积也用一个栈,每次把新的面积覆盖范围内的所有的面积出栈,剩下到最后的就是相互独立的了

将这些面积加起来,并且减去下面的砖块就可以了

class Solution {
public:
    int trap(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n<=2)return 0;
        stack<pair<int,int> > s;
        stack<pair<pair<int,int>,int> > areas;
        vector<int> blockSum;
        blockSum.resize(n,0);
        s.push(pair<int,int>(A[0],0));
        blockSum[0]=A[0];
        int index=0;
        for(int i=1;i<n;i++){
            blockSum[i]=blockSum[i-1]+A[i];
            //consider left
            if(A[i]<=s.top().first){
                s.push(pair<int,int>(A[i],i));
            }
            else{
                pair<int,int> last=s.top();
                //clear all small than current
                while(last.first<A[i]){
                    s.pop();
                    if(s.size()==0)break;
                    last=s.top();
                }
                s.push(pair<int,int>(A[i],i));
                int area;
                int area_start,area_end;
                if(last.first<A[i]){
                    area=last.first*(i-last.second-1);
                }
                else{
                    area=A[i]*(i-last.second-1);
                }
                if(area>0){
                    area_start=last.second;
                    area_end=i;
                    if(areas.size()==0){
                        areas.push(pair<pair<int,int>,int>(pair<int,int>(area_start,area_end),area));
                    }else{
                        while(areas.size()>0&&areas.top().first.first>=area_start&&areas.top().first.second<=area_end){
                            areas.pop();
                        }
                        areas.push(pair<pair<int,int>,int>(pair<int,int>(area_start,area_end),area));
                    }
                }
            }
        }
        if(areas.size()==0)return 0;
        else{
            int sum=0;
            int bsum=0;
            while(areas.size()!=0){
                sum+=areas.top().second;
                bsum+=blockSum[areas.top().first.second-1]-blockSum[areas.top().first.first];
                areas.pop();
            }
            return sum-bsum;
        }
    }
};
View Code

 

 

 

posted @ 2013-09-24 22:39  懒猫欣  阅读(184)  评论(0)    收藏  举报