题目链接:力扣
不得不说,LeetCode有的困难题还是过于简单,相比于CodeForces各个知识点杂合在一起考法来说,这种单一的知识点还是很水的。
10分钟写完代码,单调栈做法
#include
using namespace std;
int trap(vector& height) {
stacksta, val;
int arrayCount = height.size();
int answer = 0;
for(int i=0; iint cur = height[i];
int minValue = 0, length = 0;
while(sta.size() && sta.top() < cur){
int topValue = sta.top();
int curLen = val.top();
val.pop();
sta.pop();
answer = answer + (topValue - minValue) * length;
minValue = topValue;
length = length + curLen;
}
if(sta.size()){
answer = answer + (cur - minValue) * length;
}
// printf("curcur:%d answer:%d\n", cur, answer);
sta.push(cur);
val.push(length + 1);
}
return answer;
}
int main()
{
int n;
vectorG;
cin>>n;
for(int i=1;i<=n;++i){
int val;
cin>>val;
G.push_back(val);
}
printf("%d %d\n", trap(G), G.size());
}
/*
12
0 1 0 2 1 0 1 3 2 1 2 1
6
4 2 0 3 2 5
*/