42. 接雨水

This commit is contained in:
2025-09-08 23:05:13 +08:00
parent aad0631b91
commit 43c0feea86
2 changed files with 6084 additions and 0 deletions

6053
test.txt Normal file

File diff suppressed because one or more lines are too long

31
test007.cpp Normal file
View File

@@ -0,0 +1,31 @@
class Solution {
public:
int trap(vector<int>& h) {
int n = h.size();
using pii = pair<int, int>;
using ll = long long;
stack<pii> stk;
int ret = 0;
for(int i = 0; i < n; i++){
ll sum = 0;
ll W = 0;
int lastH = 0;
while(!stk.empty() && stk.top().second < h[i]){
lastH = stk.top().second;
W += stk.top().first;
sum += 1LL * stk.top().first * stk.top().second;
stk.pop();
}
if(stk.empty()){
ret += W * lastH - sum;
stk.push({1, h[i]});
}else{
ret += W * h[i] - sum;
stk.push({W + 1, h[i]});
}
}
return ret;
}
};