AcWing 1574. 接雨水
原题链接
简单
作者:
WhiteTee
,
2024-11-28 21:29:30
,
所有人可见
,
阅读 2
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
int trap(vector<int>& heights) {
int n = heights.size();
if (n <= 2) return 0; // 如果柱子少于3个,不可能存水
int ans = 0;
stack<int> st;
for (int i = 0; i < n; i++) {
while (!st.empty() && heights[i] > heights[st.top()]) {
int prev = st.top();
st.pop();
if (st.empty()) break;
int left = st.top();
int width = i - left - 1;
int height = min(heights[left], heights[i]) - heights[prev];
ans += width * height;
}
st.push(i);
}
return ans;
}
int main() {
int n;
cin >> n;
vector<int> heights(n);
for (int i = 0; i < n; i++) {
cin >> heights[i];
}
cout << trap(heights) << endl;
return 0;
}