Use the stack structure to resolve.
#include <iostream>#include<stack>using namespacestd;classSolution { Public: intTrapintA[],intN) {
if(n<3){ return 0; }
Stack<int>Water_stack; intbegin=0; intres=0;
for(inti =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; }
intEnd=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 (); } }
returnRes; }};intMainintargcChar**argv) {solution S; inta[]={0,1,0,2,1,0,1,3,2,1,2,1}; cout<<s.trap (A, A); return 0;}
Writing is not perfect, it seems to use the stack and stack, in fact, no stack can be solved.
Trapping Rain Water