ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

16234๋ฒˆ: ์ธ๊ตฌ ์ด๋™

N×Nํฌ๊ธฐ์˜ ๋•…์ด ์žˆ๊ณ , ๋•…์€ 1×1๊ฐœ์˜ ์นธ์œผ๋กœ ๋‚˜๋ˆ„์–ด์ ธ ์žˆ๋‹ค. ๊ฐ๊ฐ์˜ ๋•…์—๋Š” ๋‚˜๋ผ๊ฐ€ ํ•˜๋‚˜์”ฉ ์กด์žฌํ•˜๋ฉฐ, rํ–‰ c์—ด์— ์žˆ๋Š” ๋‚˜๋ผ์—๋Š” A[r][c]๋ช…์ด ์‚ด๊ณ  ์žˆ๋‹ค. ์ธ์ ‘ํ•œ ๋‚˜๋ผ ์‚ฌ์ด์—๋Š” ๊ตญ๊ฒฝ์„ ์ด ์กด์žฌํ•œ๋‹ค. ๋ชจ๏ฟฝ๏ฟฝ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์ด์ „์— ๋‹ค๋ฃฌ ์•ˆ์ „ ์˜์—ญ, ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ ๋ฌธ์ œ์™€ ๊ฐ™์ด `Floodfil`์„ ํ™œ์šฉํ•˜์—ฌ, ์ ‘๊ทผ ๊ฐ€๋Šฅํ•œ ์˜์—ญ์„ ํŒ๋‹จํ•˜๊ณ  ๊ทธ์— ๋”ฐ๋ผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ด ๋ฌธ์ œ์—์„œ๋Š” ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ์˜์—ญ์— ๋Œ€ํ•œ ์กฐ๊ฑด๊ณผ ๋ฐฉ๋ฌธ ํ›„์— ๊ธฐ์กด ์ธ๊ตฌ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ ๋ถ€๋ถ„์ด ์ถ”๊ฐ€๋œ ๋ฌธ์ œ์ด๋‹ค.

 

 ํ˜„์žฌ ๊ตญ๊ฐ€๋กœ๋ถ€ํ„ฐ ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ์ธ์ ‘ ๊ตญ๊ฐ€๋Š” `L <= abs(ํ˜„์žฌ ๊ตญ๊ฐ€ - ์ธ์ ‘ ๊ตญ๊ฐ€) <= R`์ด๋ผ๋Š” ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ๋งŒ์•ฝ ์—ฐํ•ฉ๊ตญ์ด 1 ์ด์ƒ (ํ˜„์žฌ ๊ตญ๊ฐ€ ์ œ์™ธ)๋ผ๋ฉด ์ธ๊ตฌ์˜ ์ˆ˜๋ฅผ ๋ชจ๋“  `์—ฐํ•ฉ๊ตญ๊ฐ€์˜ ์ธ๊ตฌ์ˆ˜์˜ ํ•ฉ / ์—ฐํ•ฉ๊ตญ๊ฐ€์˜ ์ˆ˜`๋กœ ๋ณ€๊ฒฝํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ์ด๋ฅผ BFS๋ฅผ ํ†ตํ•ด ์ฒ˜๋ฆฌํ•˜๋ฉด ๋ฌธ์ œ๋ฅผ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from collections import deque


def visitable(x, y):
    return 0 <= x < n and 0 <= y < n and not visited[x][y]


def bfs(start):
    q = deque([start])
    cur_united = [start]

    while q:
        x, y = q.popleft()

        for dx, dy in dirs:
            next_x, next_y = x + dx, y + dy

            if visitable(next_x, next_y) and \
                    l <= abs(populations[x][y] - populations[next_x][next_y]) <= r:
                visited[next_x][next_y] = True
                q.append((next_x, next_y))
                cur_united.append([next_x, next_y])

    # ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•˜๋Š” ๊ตญ๊ฐ€๋Š” ํฌํ•จํ•˜๋ฏ€๋กœ 1 ์ด์ƒ์ธ ๊ฒฝ์šฐ ๊ตญ๊ฒฝ์ด ์—ด๋ฆฐ ์ƒํƒœ.
    if len(cur_united) > 1:
        # ๋ฌธ์ œ์˜ ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ƒˆ๋กœ์šด ์ธ๊ตฌ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•จ.
        new_population = sum(populations[x][y] for x, y in cur_united) // len(cur_united)
        for x, y in cur_united:
            populations[x][y] = new_population
        return 1

    return 0


if __name__ == '__main__':
    dirs = ((0, 1), (0, -1), (1, 0), (-1, 0))
    n, l, r = map(int, stdin.readline().split())
    populations = [list(map(int, stdin.readline().split())) for _ in range(n)]
    cnt = 0

    while True:
        visited = [[False] * n for _ in range(n)]
        num_of_united = 0

        for i in range(n):
            for j in range(n):
                if not visited[i][j]:
                    visited[i][j] = True
                    num_of_united += bfs([i, j])

        # ๊ตญ๊ฒฝ์ด ์—ด๋ฆฌ์ง€ ์•Š๋Š” ๋‹ค๋ฉด, ๋” ์ด์ƒ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•˜์ง€ ์•Š์•„๋„ ๋จ.
        if not num_of_united:
            break

        cnt += 1

    print(cnt)

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€