class Solution {
public:
int trap(vector<int>& height) {
stack<int> st;
st.push(0);
int n = height.size();
int ans = 0;
for (int i = 1; i < n; i++) {
while (!st.empty() && height[st.top()] < height[i]) {
int mid = st.top();
st.pop();
if (!st.empty()) {
int h = min(height[st.top()], height[i]) - height[mid];
int w = i - st.top() - 1; // 注意减一,只求中间宽度
ans += h * w;
}
}
st.push(i);
}
return ans;
}
};