Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1] , return 6 .
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!
Hide TagsArray Stack, pointers
Good happy, logic so troublesome topic, wrote once not wrong, submitted directly over. Do the previous topic may be easy to think, if you use a stack to maintain subscript, its corresponding sequence is non-ascending, in the back of the work to maintain the stack.in a non-descending stack, if the value considered is smaller than top, the stack is added. If it is greater than the top value, the value is less than, and the return value is calculated. For example, when traversing to IDX = 5, the subscript inside the stack is: 3,4 a[5]<a[4], so join the stack, and then traverse to IDX = 6, stack is: 3,4,5 then pops up stack top, then calculates the pop-up value puddle, this time only need to calculate the red The part, through the stack pops up after the top=4, pit = 5, and wall = 6, the time to update, and then update the stack into: 3,4,6, then is to traverse the IDX = 7, this time the popup is 6, through top=4, pit 6, wall =7 calculation, this value is 0. Because the stack top is still less than, so continue to eject, and then calculate, top=3, Pit 4, Wall 7, calculated the part: at this time stack:3, continue to eject, but at this time the stack does not top, so you can end this step, will idx=7 press into the stack. Code:
1#include <iostream>2#include <stack>3 using namespacestd;4 5 classSolution {6 Public:7 intTrapintA[],intN) {8 if(n<3)return 0;9 intCuridx =0;Ten Onestack<int>Stk; A - intRetsum =0; - for(; curidx<n;curidx++){ the if(Stk.empty ()) { - Stk.push (CURIDX); - Continue; - } + intStktop =stk.top (); - if(a[stktop]>=A[curidx]) { + Stk.push (CURIDX); A Continue; at } - while(!Stk.empty ()) { - intDIT =Stktop; - Stk.pop (); - if(Stk.empty ()) Break; -Stktop =stk.top (); inRetsum + = (min (A[stktop],a[curidx])-a[dit]) * (Curidx-stktop-1); - if(A[stktop]>a[curidx]) Break; to } + Stk.push (CURIDX); - } the returnretsum; * } $ };Panax Notoginseng - intMain () the { + inta[]= {0,1,0,2,1,0,1,3,2,1,2,1}; A solution Sol; theCout<<sol.trap (A,sizeof(A)/sizeof(int)) <<Endl; + return 0; -}View Code
[Leetcode] trapping Rain water stack