提交时间:2024-08-21 17:10:39

运行 ID: 180657

#include <iostream> #include <vector> #include <algorithm> using namespace std; int trap(vector<int>& height) { if (height.empty()) return 0; int n = height.size(); int left = 0, right = n - 1; int left_max = 0, right_max = 0; int total_water = 0; while (left < right) { if (height[left] < height[right]) { if (height[left] >= left_max) { left_max = height[left]; } else { total_water += left_max - height[left]; } left++; } else { if (height[right] >= right_max) { right_max = height[right]; } else { total_water += right_max - height[right]; } right--; } } return total_water; } int main() { int n; cin >> n; vector<int> height(n); for (int i = 0; i < n; i++) { cin >> height[i]; } cout << trap(height); return 0; }