import java.io.*;
import java.util.*;
public class rainwater_14719 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int h = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
List<Integer> blocks = new ArrayList<>();
st = new StringTokenizer(br.readLine());
for (int i = 0; i < w; i++){
blocks.add(Integer.parseInt(st.nextToken()));
}
int result = calculater_rainwater(h, w, blocks);
System.out.println(result);
}
public static int calculater_rainwater (int h, int w, List<Integer> blocks) {
int total = 0;
for (int i = 1; i < w-1; i++){
int left_max = Collections.max(blocks.subList(0, i));
int right_max = Collections.max(blocks.subList(i+1, blocks.size()));
if (blocks.get(i) < left_max && blocks.get(i) < right_max) {
total += Math.min(left_max, right_max) - blocks.get(i);
}
}
return total;
}
}
코드의 로직을 리스트 형태로 설명하면 다음과 같습니다:
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function calculateRainwater(h, w, blocks) {
let total = 0;
for (let i = 1; i < w - 1; i++) {
const leftMax = Math.max(...blocks.slice(0, i));
const rightMax = Math.max(...blocks.slice(i + 1));
if (blocks[i] < leftMax && blocks[i] < rightMax) {
total += Math.min(leftMax, rightMax) - blocks[i];
}
}
return total;
}
rl.on("line", (line) => {
const input = line.split(" ");
const h = parseInt(input[0]);
const w = parseInt(input[1]);
rl.on("line", (line) => {
const blocks = line.split(" ").map(Number);
const result = calculateRainwater(h, w, blocks);
console.log(result);
rl.close();
});
});
h, w = map(int, input().split())
blocks = list(map(int, input().split()))
def calculate_rainwater(h, w, blocks):
total = 0
for col in range(1, w-1):
left_max = max(blocks[:col])
right_max = max(blocks[col+1:])
if blocks[col] < left_max and blocks[col] < right_max:
total += min(left_max, right_max) - blocks[col]
return total
result = calculate_rainwater(h, w, blocks)
print(result)