본문 바로가기
programming/알고리즘

[백준, 14719, G5] 빗물

by s2econd.blue 2022. 10. 20.

0. 문제 링크

https://www.acmicpc.net/problem/14719

 

14719번: 빗물

첫 번째 줄에는 2차원 세계의 세로 길이 H과 2차원 세계의 가로 길이 W가 주어진다. (1 ≤ H, W ≤ 500) 두 번째 줄에는 블록이 쌓인 높이를 의미하는 0이상 H이하의 정수가 2차원 세계의 맨 왼쪽 위치

www.acmicpc.net


1. 문제 핵심

  1. 블록에 의해 고이는 물의 총량을 구하는 문제

2. 문제 접근

  1. 가로, 세로 500개밖에 되지 않기 때문에 완전 탐색을 하면 된다고 생각했습니다.
  2. 가로 0부터 H-1까지 확인하며 첫 블록 이후로 그 다음 블록까지 빗물에 의해 고일 수 있는 양을 한 줄씩 계산해주고 한 줄이 끝나면 answer에 더해주었습니다.

3. 코드 분석

  1.  

4. 베스트 코드 분석

  1.  

5. 코드

import java.io.*;
import java.util.*;

class Main {
	static class reader {
		int bufferSize = 1 << 18;
		byte[] buffer = new byte[bufferSize];
		DataInputStream dis = new DataInputStream(System.in);
		int bufferPointer = 0, bytesRead = 0;

		byte read() throws IOException {
			if (bufferPointer == bytesRead) {
				bytesRead = dis.read(buffer, bufferPointer = 0, bufferSize);
				if (bytesRead == -1)
					buffer[0] = -1;
			}
			return buffer[bufferPointer++];
		}

		public int nextInt() throws IOException {
			int ret = 0;
			byte c = read();
			while (c <= ' ') {
				c = read();
			}
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}
	}

	public static void main(String[] args) throws IOException {
//		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//		StringTokenizer st = new StringTokenizer(br.readLine());
		reader br = new reader();
		int H = br.nextInt();
		int W = br.nextInt();

		boolean[][] bd = new boolean[H][W];
		int lv;
		for (int i = 0; i < W; i++) {
			lv = br.nextInt();
			for (int j = 0; j < lv; j++) {
				bd[H - 1 - j][i] = true;
			}
		}
		boolean wall;
		int cnt, answer = 0;
		for (int i = 0; i < H; i++) {
			// 처리되지 않았다면 초기화
			wall = false;
			cnt = 0;
			for (int j = 0; j < W; j++) {
				// 블록이라면
				if (bd[i][j]) {
					// 블록이 시작되지 않았다면 시작 전환
					if (!wall)
						wall = true;
					// 블록이 시작되었는데 빗물이 하나도 없다면 == 블록이 이어져있는 경우
					else if (cnt == 0)
						continue;
					// 블록이 시작되었는데 빗물이 있다면
					else if (cnt != 0) {
						// 벽 닫아주고
						answer += cnt;
						cnt = 0;
					}
				}
				// 빈공간이라면
				else {
					// 벽이 시작되었다면
					if (wall)
						cnt++;
				}
			}

		}
		System.out.println(answer);
	}
}

'programming > 알고리즘' 카테고리의 다른 글

[백준, G3, 2539] 모자이크  (0) 2022.10.23
[백준, 15486, G5] 퇴사 2  (0) 2022.10.20
[백준, 1956, G4] 운동  (0) 2022.10.20
[백준, 7662, G4] 이중 우선순위 큐  (0) 2022.10.18
[백준, 13905, G4, MST] 세부  (0) 2022.10.18

댓글