标签:
给定n个非负整数,分别代表围栏的高度,计算给定的这组数字代表的围栏能够容纳多少水,如图所示。
输入
0 1 0 2 1 0 1 3 2 1 2 1
输出
6
对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积是min(max_left, max_right) - height。所以可以先扫描一遍,找到最高的柱子,将数组分为两半,然后分别进行处理。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> bars = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int height = 0;
//寻找最高的柱子
for (int i = 0; i < bars.size(); i++)
if (bars[i] > bars[height])
height = i;
int water = 0;
//左边储水量
for (int i = 0, peak = 0; i < height; i++)
if (bars[i] > peak)
peak = bars[i];
else
water += peak - bars[i];
//右边储水量
for (int i = bars.size() - 1, top = 0; i > height; i--)
if (bars[i] > top)
top = bars[i];
else
water += top - bars[i];
cout << water << endl;
return 0;
}
标签:
原文地址:http://blog.csdn.net/sin_geek/article/details/51507695