# （算法）Trapping Rain Water I

## 题目：

Given n non-negative integers representing an elevation map where the width of each bar is 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`.

## 代码：

```#include<iostream>
#include<vector>
#include<stdlib.h>

using namespace std;

int MaxTrappingWater(const vector<int> &water){
int sz=water.size();

vector<int> preMaxWater(sz);
preMaxWater[0]=0;
for(int i=1;i<sz;i++){
if(water[i]>preMaxWater[i-1])
preMaxWater[i]=water[i];
else
preMaxWater[i]=preMaxWater[i-1];
}

vector<int> sufMaxWater(sz);
sufMaxWater[sz-1]=0;
for(int i=sz-2;i>=0;i--){
if(water[i]>sufMaxWater[i+1])
sufMaxWater[i]=water[i];
else
sufMaxWater[i]=sufMaxWater[i+1];
}

int sum=0;
for(int i=0;i<sz;i++){
sum+=max(0,min(preMaxWater[i],sufMaxWater[i])-water[i]);
}

return sum;
}

int main(){
int n;
while(cin>>n){
vector<int> water(n,0);
for(int i=0;i<n;i++)
cin>>water[i];

cout << MaxTrappingWater(water) <<endl;
}

return 0;
}```

原文作者：AndyJee
原文地址: https://www.cnblogs.com/AndyJee/p/4821590.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。