/*
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
*/
#include "iostream"
#include "stack"
#include "vector"
using namespace std;
class Solution
{
public:
int trap(vector<int> &height)
{
if (height.size() < 3)
{
return 0;
}
int i = 0;
int ans = 0, n;
int max_index = 0;
for (i = 1; i < height.size(); i++)
{
if (height[i] > height[max_index])
{
max_index = i;
}
}
stack<int> h;
// 从左向右
i = 0;
int left;
while (height[i] < height[i + 1])
{
i++;
if (i + 1 > max_index)
{
break;
}
}
left = height[i];
for (i++; i <= max_index; i++)
{
n = height[i];
if (n < left)
{
h.push(n);
}
else
{
while (!h.empty())
{
ans += left - h.top();
h.pop();
}
left = n;
}
}
// 从右向左
i = height.size() - 1;
int right;
while (height[i] < height[i - 1] && i > max_index)
{
i--;
if (i - 1 < max_index)
{
break;
}
}
right = height[i];
for (i--; i >= max_index; i--)
{
n = height[i];
if (n < right)
{
h.push(n);
}
else
{
while (!h.empty())
{
ans += right - h.top();
h.pop();
}
right = n;
}
}
return ans;
}
};
int main(int argc, char const *argv[])
{
vector<int> height;
int x;
while (true)
{
cin >> x;
height.push_back(x);
if (cin.get() == '\n')
break;
}
Solution so;
x = so.trap(height);
cout << x << endl;
return 0;
}