Code Part I: The 14th question of rainwater
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute
How much water it was able to the trap after raining.
For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
Analysis:Solutions 1for each pillar, find the tallest pillar on the left and right side, the area that the pillar can hold is min (Max_left,max_right)-height. So,1. Scan from left to right, and for each pillar, the left maximum value is obtained;2. Scan from right to left, for each column, the maximum right value;3. Scan again and add up the area of each pillar. the time complexity of the first scheme O (n), the spatial complexity is O (n); Solutions 21. Scan once and find the highest pillar, which divides the array into two halves;2. Handle the left half;3. Handle the right half. the time complexity of the second scheme is O (N), and the spatial complexity is O (1); Solutions 3use a stack, with a stack of auxiliary, less than the top of the stack of elements, greater than or equal to the stack at the top of the stack all less than or equal whenthe elements of the previous value are all out of the stack. time complexity O (n), spatial complexity O (n)
#include <iostream>#include<stack>using namespacestd;intMinintNintm) { if(n>m) {returnm; } Else returnN;}intWater (intA[],intN) { inti; Const intCount=N; intB[count]; intC[count]; intsum1=0; for(i =1; I < count; i++) { if(a[i]>sum1) {sum1=A[i]; } B[i]=sum1; } intJ; intSum2=0; for(j = count-2; J >=0; j--) { if(a[j]>sum2) {sum2=A[j]; } C[j]=sum2; } intsum=0; intK; for(k =1; K < count-1; k++) {sum+=min (B[k],c[k])-A[k]; } returnsum;}intWater2 (intA[],intN) { intI=0; intmax=0; intpos=0; for(i =0; I < n; i++) { if(a[i]>max) {Max=A[i]; POS=i; } } intJ; intsum1=a[0]; intans=0; for(j =1; J < Pos; J + +) { if(a[j]>=sum1) {sum1=A[j]; } Else{ans+=sum1-A[j]; } } intsum2=a[n-1]; intK; for(k = n2; k>pos; k--) { if(a[k]>sum2) {sum2=A[k]; } Else{ans+=sum2-A[k]; } } returnans;}intWater3 (intA[],intN) {Stack<pair<int,int>>s; intWater =0; for(inti =0; I < n; ++i) {intHeight =0; while(!S.empty ()) { //dispose of elements in the stack that are shorter or higher than the current element intBar =S.top (). First; intpos =S.top (). Second; //bar, height, a[i] The hollow of the threeWater + = (min (bar, a[i])-height) * (I-pos-1); Height=Bar; if(A[i] < bar)//hit a higher than the current element, jump out of the loop Break; ElseS.pop ();//pop up the top of the stack because the element is finished and no longer needed} s.push (Make_pair (a[i], i)); } returnWater;}intMain () {inta[ A]={0,1,0,2,1,0,1,3,2,1,2,1}; intAns1=water (A, A); cout<<"ans1 is"<<ans1<<Endl; intAns2=water2 (A, A); cout<<"Ans2 is"<<ans2<<Endl; intAns3=water3 (A, A); cout<<"Ans3 is"<<ans3<<Endl; return 0;}
Code Part I: The 14th question of rainwater