ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [๋ฐฑ์ค€] 9372 ์ƒ๊ทผ์ด์˜ ์—ฌํ–‰ with Python
    PS 2022. 2. 22. 20:17
    728x90
    ๋ฐ˜์‘ํ˜•

    ๐Ÿ“Œ BOJ 9372 ์ƒ๊ทผ์ด์˜ ์—ฌํ–‰

    ๐Ÿ’ก ์กฐ๊ฑด

    1. N๊ฐœ๊ตญ์„ ์—ฌํ–‰ํ•  ์ƒ๊ทผ์ด์—๊ฒŒ ๊ฐ€์žฅ ์ ์€ ๋น„ํ–‰๊ธฐ๋ฅผ ํƒ€๊ณ  ์—ฌํ–‰ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋„์™€์ฃผ์ž.

    2. ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ˆ˜ T(T โ‰ค 100)

    3. ์ฒซ ๋ฒˆ์งธ ์ค„์—๋Š” ๊ตญ๊ฐ€์˜ ์ˆ˜ N(2 โ‰ค N โ‰ค 1 000)๊ณผ ๋น„ํ–‰๊ธฐ์˜ ์ข…๋ฅ˜ M(1 โ‰ค M โ‰ค 10 000) ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.
      ์ดํ›„ M๊ฐœ์˜ ์ค„์— a์™€ b ์Œ๋“ค์ด ์ž…๋ ฅ๋œ๋‹ค. a์™€ b๋ฅผ ์™•๋ณตํ•˜๋Š” ๋น„ํ–‰๊ธฐ๊ฐ€ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. (1 โ‰ค a, b โ‰ค n; a โ‰  b)
      ์ฃผ์–ด์ง€๋Š” ๋น„ํ–‰ ์Šค์ผ€์ค„์€ ํ•ญ์ƒ ์—ฐ๊ฒฐ ๊ทธ๋ž˜ํ”„๋ฅผ ์ด๋ฃฌ๋‹ค.

    4. ๊ทธ๋ž˜ํ”„์ด๋ก , ์œ ๋‹ˆ์˜จ-ํŒŒ์ธ๋“œ ์œ ํ˜•์˜ ๋ฌธ์ œ

    ๐Ÿ–ฅ ์†Œ์Šค ์ฝ”๋“œ

    from sys import stdin
    
    
    def find_parent(parent, x):
        if parent[x] != x:
            parent[x] = find_parent(parent, parent[x])
        return parent[x]
    
    
    def union_parent(a, b, parent):
        a = find_parent(parent, a)
        b = find_parent(parent, b)
    
        if a < b:
            parent[a] = b
        else:
            parent[b] = a
    
    
    for test_case in range(int(stdin.readline())):
        n, m = map(int, stdin.readline().split())
        nations = [x for x in range(n + 1)]
        res = 0
        for _ in range(m):
            a, b = map(int, stdin.readline().split())
            if find_parent(nations, a) != find_parent(nations, b):
                union_parent(a, b, nations)
                res += 1
    
        print(res)

    ๐Ÿ”– ์˜ˆ์ œ ๋ฐ ์‹คํ–‰๊ฒฐ๊ณผ

    ์˜ˆ์ œ

    2
    3 3
    1 2
    2 3
    1 3
    5 4
    2 1
    2 3
    4 3
    4 5

    ์‹คํ–‰๊ฒฐ๊ณผ

    2
    4

    โŒจ๏ธ ๋ฌธ์ œ ํ’€์ด

    1. Union-Find ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

    2. parent ๋ฆฌ์ŠคํŠธ์—์„œ ๊ฐ ๊ตญ์€ ๋ณธ์ธ์˜ ๋ฒˆํ˜ธ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.
      ๋งŒ์•ฝ ์ƒ๊ทผ์ด๊ฐ€ a๊ตญ๊ฐ€์—์„œ b ๊ตญ๊ฐ€๋ฅผ ๊ฐ„๋‹ค๊ณ  ์ž…๋ ฅ์„ ๋ฐ›์•˜์œผ๋ฉด, a์™€ b ๊ตญ๊ฐ€์˜ parent ๋ฅผ ์ฐพ๊ณ , ๋งŒ์•ฝ ์„œ๋กœ ๊ฐ™์ง€ ์•Š๋‹ค๋ฉด ๊ฐ™์€ ๋ถ€๋ชจ์— ์†ํ•˜๋„๋ก ๋ณ€๊ฒฝํ•œ๋‹ค.

    3. (2)๋ฒˆ ์ž‘์—…์„ ๋งˆ์นœ ๋’ค, res + 1

    4. res ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

    ๐Ÿ’พ ๋Š๋‚€์ 

    1. ๊ณตํ•ญ์ด๋ผ๋Š” ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋˜ ๊ธฐ์–ต์ด ์žˆ๊ณ , ์œ ๋‹ˆ์˜จ-ํŒŒ์ธ๋“œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•ด ์‹œ๋„ํ•ด ๋ดค์—ˆ๋˜ ๊ธฐ์–ต์ด ์žˆ์Šต๋‹ˆ๋‹ค.
    2. ์œ ํŒŒ๋กœ ํ•œ๋ฒˆ์— ํ’€์—ˆ๋˜ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.