Topic:
Given n non-negative integers representing an elevation map where the width of each bar are 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
.
Ideas:
The title means that given a nonnegative array of integers, each number of the array represents the height of the column, and if the pillars are formed into a container, how much water can be filled?
The idea is that the capacity of each pillar (h) at its location can be determined by the maximum height of all the pillars in front of it preheight and the highest height of all pillars behind it postheight,
The capacity of the loaded water equals max (0,min (preheight-postheight)-h);
You can therefore calculate the maximum value of the array of prefixes in a given array (for example, Premax[i], which represents the maximum value of arrays from 0 to i-1), and the maximum value of the suffix array (such as Postmax[i], which represents the maximum value of the array from I to the n-1 position), you can use the above formula to compute the water capacity per location , and finally add up is the total capacity.
Code:
#include <iostream>#include<vector>#include<stdlib.h>using namespacestd;intMaxtrappingwater (Constvector<int> &water) { intsz=water.size (); Vector<int>Premaxwater (SZ); premaxwater[0]=0; for(intI=1; i<sz;i++){ if(water[i]>premaxwater[i-1]) Premaxwater[i]=Water[i]; ElsePremaxwater[i]=premaxwater[i-1]; } Vector<int>Sufmaxwater (SZ); Sufmaxwater[sz-1]=0; for(inti=sz-2; i>=0; i--){ if(water[i]>sufmaxwater[i+1]) Sufmaxwater[i]=Water[i]; ElseSufmaxwater[i]=sufmaxwater[i+1]; } intsum=0; for(intI=0; i<sz;i++) {sum+=max (0, Min (Premaxwater[i],sufmaxwater[i])-Water[i]); } returnsum;}intMain () {intN; while(cin>>N) {Vector<int> Water (N,0); for(intI=0; i<n;i++) Cin>>Water[i]; cout<< maxtrappingwater (water) <<Endl; } return 0;}
Algorithm Trapping Rain Water I