AcWing 1574. 接雨水——Java代码版——单调栈
原题链接
简单
作者:
三玖天下第一
,
2021-03-26 14:29:17
,
所有人可见
,
阅读 537
import java.io.*;
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
ArrayDeque<Integer> q = new ArrayDeque<>(10000+10);
int m = Integer.parseInt(reader.readLine().trim());
String[] temp = reader.readLine().split(" ");
int[] h = new int[m+2];
int res = 0;
for (int i = 0; i < m; i++) {
h[i] = Integer.parseInt(temp[i]);
}
for (int i = 0; i < m; i++) {
int last = 0;//用于存放上一个较小的高度值是多少
while(!q.isEmpty() && h[q.peek()] <= h[i]){
//当队列非空且队头元素小于当前元素时,计算两者之间的面积
res += (h[q.peek()] - last) * (i - q.peek() - 1);
//更新高度值
last = h[q.peek()];
q.pop();
}
if (!q.isEmpty()){
res += (h[i] - last) * (i - q.peek() - 1);
}
q.push(i);
}
System.out.println(res);
}
}
可以,很简洁