classSolution { public: inttrap(vector<int>& height){ int ans = 0; stack<int> st; for (int i = 0; i < height.size(); i++) { while (!st.empty() && height[i] >= height[st.top()]) { int bottom_h = height[st.top()]; st.pop(); if (st.empty()) { break; } int left = st.top(); int dh = min(height[left], height[i]) - bottom_h; // 面积的高 ans += dh * (i - left - 1); } st.push(i); } return ans; } };
public: inttrapRainWater(vector<vector<int>>& heightMap){ int m = heightMap.size(), n = heightMap[0].size(); priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> pq; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { pq.push({heightMap[i][j], i, j}); heightMap[i][j] = -1; } } } int ans = 0; while (!pq.empty()) { auto [min_height, i, j] = pq.top(); pq.pop(); for (auto& [dx, dy] : DIRS) { int x = i + dx; int y = j + dy; if (x >= 0 && y >= 0 && x < m && y < n && heightMap[x][y] != -1) { ans += max(min_height - heightMap[x][y], 0); pq.push({max(min_height, heightMap[x][y]), x, y}); heightMap[x][y] = -1; } } } return ans; } };
public: // 类似题目: 84. 柱状图中最大的矩形 intsumSubarrayMins(vector<int>& arr){ int n = arr.size(); // 左边界 left[i] 为左侧严格小于 arr[i] 的最近元素位置(不存在时为 -1) vector<int> left(n, -1); stack<int> st; for (int i = 0; i < n; i++) { while (!st.empty() && arr[st.top()] >= arr[i]) st.pop(); if (!st.empty()) left[i] = st.top(); st.push(i); }
st = stack<int>(); // 右侧找 <= 是为了避免重复统计 // 右边界 right[i] 为右侧小于等于 arr[i] 的最近元素位置(不存在时为 n) vector<int> right(n, n); for (int i = n - 1; i >= 0; i--) { while (!st.empty() && arr[st.top()] > arr[i]) st.pop(); if (!st.empty()) right[i] = st.top(); st.push(i); } long ans = 0l; for (int i = 0; i < n; i++) { ans += (long)arr[i] * (i - left[i]) * (right[i] - i); } return ans % MOD; } };