Algorithms/Algorithms

์ด๋ถ„ ๊ทธ๋ž˜ํ”„ (๋ฐฑ์ค€ 1707)

ํƒฑ์ ค 2021. 10. 8. 13:17

์ด๋ถ„๊ทธ๋ž˜ํ”„

๋ชจ๋“  ๊ผญ์ง“์ ์„ ๋นจ๊ฐ•๊ณผ ํŒŒ๋ž‘์œผ๋กœ ์ƒ‰์น ํ•˜๋˜, ๋ชจ๋“  ๋ณ€์ด ๋นจ๊ฐ•๊ณผ ํŒŒ๋ž‘ ๊ผญ์ง“์ ์„ ํฌํ•จํ•˜๋„๋ก ์ƒ‰์น ํ•  ์ˆ˜ ์žˆ๋Š” ๊ทธ๋ž˜ํ”„

์ด๋ถ„ ๊ทธ๋ž˜ํ”„์ธ์ง€ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•

๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰(BFS), ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰(DFS)์„ ์ด์šฉ → ์„œ๋กœ ์ธ์ ‘ํ•œ ์ •์ ์ด ๊ฐ™์€ ์ƒ‰์ด๋ฉด ์ด๋ถ„ ๊ทธ๋ž˜ํ”„ X
1. BFS, DFS๋กœ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ์ •์ ์„ ๋ฐฉ๋ฌธํ•  ๋•Œ๋งˆ๋‹ค ๋‘ ๊ฐ€์ง€ ์ƒ‰ ์ค‘ ํ•˜๋‚˜๋ฅผ ์น ํ•œ๋‹ค.
2. ๋‹ค์Œ ์ •์ ์„ ๋ฐฉ๋ฌธํ•˜๋ฉด์„œ ์ž์‹ ๊ณผ ์ธ์ ‘ํ•œ ์ •์ ์€ ์ž์‹ ๊ณผ ๋‹ค๋ฅธ ์ƒ‰์œผ๋กœ ์น ํ•œ๋‹ค.
3. ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•  ๋•Œ ์ž์‹ ๊ณผ ์ธ์ ‘ํ•œ ์ •์ ์˜ ์ƒ‰์ด ์ž์‹ ๊ณผ ๋™์ผํ•˜๋ฉด ์ด๋ถ„ ๊ทธ๋ž˜ํ”„๊ฐ€ ์•„๋‹ˆ๋‹ค.
4. BFS์˜ ๊ฒฝ์šฐ ์ •์ ์„ ๋ฐฉ๋ฌธํ•˜๋‹ค๊ฐ€ ๋งŒ์•ฝ ๊ฐ™์€ ๋ ˆ๋ฒจ์—์„œ ์ •์ ์„ ๋‹ค๋ฅธ ์ƒ‰์œผ๋กœ ์น ํ•ด์•ผ ํ•œ๋‹ค๋ฉด ๋ฌด์กฐ๊ฑด ์ด๋ถ„ ๊ทธ๋ž˜ํ”„๊ฐ€ ์•„๋‹ˆ๋‹ค.

 

๋ชจ๋“  ์ •์ ์„ ๋‹ค ๋ฐฉ๋ฌธํ–ˆ๋Š”๋ฐ ์œ„์™€ ๊ฐ™์€ ๊ฒฝ์šฐ๊ฐ€ ์—†๋‹ค๋ฉด ์ด๋ถ„ ๊ทธ๋ž˜ํ”„์ด๋‹ค.

โ€ป ์ด๋•Œ ์ฃผ์˜ํ•  ์ ์€ ์—ฐ๊ฒฐ ๊ทธ๋ž˜ํ”„์™€ ๋น„์—ฐ๊ฒฐ ๊ทธ๋ž˜ํ”„๋ฅผ ๋‘˜ ๋‹ค ๊ณ ๋ ค ํ•ด์•ผํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.
๊ทธ๋ž˜ํ”„๊ฐ€ ๋น„์—ฐ๊ฒฐ ๊ทธ๋ž˜ํ”„์ธ ๊ฒฝ์šฐ ๋ชจ๋“  ์ •์ ์— ๋Œ€ํ•ด์„œ ํ™•์ธํ•˜๋Š” ์ž‘์—…์ด ํ•„์š”ํ•˜๋‹ค.


์ฐธ๊ณ : https://gmlwjd9405.github.io/2018/08/23/algorithm-bipartite-graph.html

 


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

 

1707๋ฒˆ: ์ด๋ถ„ ๊ทธ๋ž˜ํ”„

์ž…๋ ฅ์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๋Š”๋ฐ, ์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ K๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ฒซ์งธ ์ค„์—๋Š” ๊ทธ๋ž˜ํ”„์˜ ์ •์ ์˜ ๊ฐœ์ˆ˜ V์™€ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ E๊ฐ€ ๋นˆ ์นธ์„ ์‚ฌ์ด์—

www.acmicpc.net

์ด๋ถ„ ๊ทธ๋ž˜ํ”„ ์˜ˆ์‹œ

from collections import deque
import sys

input = sys.stdin.readline
k = int(input())

def bfs(start):
    visited[start] = 1
    q = deque()
    q.append(start)
    while q:
        a = q.popleft()
        for i in graph[a]:
            if visited[i] == 0:
                visited[i] = -visited[a] # i์™€ ์—ฐ๊ฒฐ๋œ ์ •์ ์„ -๋กœ ๋ฐ”๊ฟ”์คŒ (์ด๋ถ„๊ทธ๋ž˜ํ”„)
                q.append(i)
            else:
                if visited[i] == visited[a]:
                    return False
    return True

for i in range(k):
    v, e = map(int, input().split())
    flag = True
    graph = [[] for i in range(v + 1)]
    visited = [0 for i in range(v + 1)]
    
    for j in range(e):
        a, b = map(int, input().split())
        graph[a].append(b)
        graph[b].append(a)
        
    for k in range(1, v + 1):
        if visited[k] == 0:
            if not bfs(k):
                flag = False
                break

    print("YES" if flag else "NO")
728x90