๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 4195 - ์นœ๊ตฌ ๋„คํŠธ์›Œํฌ

by HandHand 2021. 3. 18.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 4195๋ฒˆ

ํ’€์ด ๊ณผ์ •

์นœ๊ตฌ ๊ด€๊ณ„๋ฅผ ๊ฐฑ์‹ ํ•˜๋ฉด์„œ ์นœ๊ตฌ ๋„คํŠธ์›Œํฌ์— ๋ช‡ ๋ช…์ด ์žˆ๋Š”์ง€ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ด๋Š” ์ง๊ด€์ ์œผ๋กœ ์œ ๋‹ˆ์˜จ ํŒŒ์ธ๋“œ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์นœ๊ตฌ ๊ด€๊ณ„๊ฐ€ ์ถ”๊ฐ€๋  ๋•Œ๋งˆ๋‹ค ๊ทธ ๋‘˜์„ union ํ•ด์ค€ ๋’ค ์ƒ์„ฑ๋œ ์ง‘ํ•ฉ์˜ ํฌ๊ธฐ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
์ด๋•Œ ์ž…๋ ฅ์œผ๋กœ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง€๋ฏ€๋กœ ํ•ด์‹ฑ ์„ ํ†ตํ•ด ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋„๋ก ๋”•์…”๋„ˆ๋ฆฌ ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ•œ ๊ฒƒ์— ์œ ์˜ํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys


def union(u, v):
    u, v = find(u), find(v)

    if u == v:
        return
    if rank[u] > rank[v]:
        u, v = v, u
    parent[u] = v
    if rank[u] == rank[v]:
        rank[v] += 1
    size[v] += size[u]


def find(u):
    if parent[u] == u:
        return u
    parent[u] = find(parent[u])
    return parent[u]


if __name__ == '__main__':
    T = int(input())
    for _ in range(T):
        rank = {}
        parent = {}
        size = {}

        F = int(input())
        for _ in range(F):
            targets = list(sys.stdin.readline().split())
            for target in targets:
                if target not in parent:
                    parent[target] = target
                    size[target] = 1
                    rank[target] = 1

            union(targets[0], targets[1])
            print(size[find(targets[0])])
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 2563 - ์ƒ‰์ข…์ด  (0) 2021.03.18
BOJ 1963 - ์†Œ์ˆ˜ ๊ฒฝ๋กœ  (0) 2021.03.18
BOJ 17626 - Four Squares  (0) 2021.03.18
BOJ 1303 - ์ „์Ÿ - ์ „ํˆฌ  (0) 2021.03.18
BOJ 1260 - DFS์™€ BFS  (0) 2021.03.18

๐Ÿ’ฌ ๋Œ“๊ธ€