题目:接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

 

输入样例

12
0 1 0 2 1 0 1 3 2 1 2 1

输出样例

6

 

输入样例

9
4 2 0 3 2 5

输出样例

9

 

代码

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    int max_height(vector<int>& height, int start, int end)
    {
        int max_value = 0;
        for (int i = start; i <= end;i++)
        {
            if (max_value < height[i])
            {
                max_value = height[i];
            }
        }
        return max_value;
    }
    int trap(vector<int>& height) 
    {
        int len = height.size();
        int water = 0;
        for (int i = 1; i < len - 1; i++)
        {
            int left_max = max_height(height, 0, i - 1);
            int right_max = max_height(height, i + 1, len - 1);
            if (height[i] < min(left_max, right_max))
            {
                water += (min(left_max, right_max) - height[i]);
            }
        }
        return water;
    }
};
int main()
{
    vector<int> vec;
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        int tmp;
        cin >> tmp;
        vec.push_back(tmp);
    }
    Solution sol;
    
    cout << sol.trap(vec) << endl;
    return 0;
}

  

posted on 2022-10-03 18:56  yc-limitless  阅读(24)  评论(0)    收藏  举报