Algorithm Trapping Rain Water I

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.