-
[๋ฐฑ์ค] ์ด๋ถ ๊ทธ๋ํ(๊ณจ๋4)๐ปProgramming/Algorithm 2025. 9. 10. 18:30
๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/7569
์ด๋ถ ๊ทธ๋ํ(Bipartite Graph)์ ์ ์
- ์ ์ ์ ๋ ๊ทธ๋ฃน์ผ๋ก ๋๋ ์ ์๋ ๊ทธ๋ํ
- ์ด๋ถ ๊ทธ๋ํ๊ฐ ๋ ์ ์๋ ์กฐ๊ฑด: ๊ฐ์ ๊ทธ๋ฃน ์์๋ ๊ฐ์ ์ด ์์ด์ผํจ
- ์ฆ ๋ชจ๋ ๊ฐ์ ์ ๋ค๋ฅด ๊ทธ๋ฃน์ ์ฐ๊ฒฐ
์์
๊ทธ๋ฃน 1: {A, B}
๊ทธ๋ฃน 2: {C, D}
๊ฐ์ : A-C, A-D, B-C, B-D
→ ๊ฐ๋ฅ โ๊ฐ์ : A-B
→ A์ B๊ฐ ๊ฐ์ ๊ทธ๋ฃน → โbfs ์ด์ฉ ๋ฌธ์
- is_bipartite ํจ์์์ ์ ์ฒด for ๋ฌธ์ ๋๋ ์ด์ : ๊ทธ๋ํ๊ฐ ์ฐ๊ฒฐ ๊ทธ๋ํ๊ฐ ์๋ ์๋ ์๊ธฐ ๋๋ฌธ์ <- ๋ง์ฝ ์ฐ๊ฒฐ ๊ทธ๋ํ๋ผ๋ ๋ณด์ฅ์ด ์์ผ๋ฉด ๊ตณ์ด for๋ฌธ ๋ ํ์ x
- bfs ๊ตฌํ ์ฝ๋
- ์ธ์ ๋ ธ๋๋ค์ ๋ชจ๋ ๋๋ฉด์ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๋ ธ๋์ธ ๊ฒฝ์ฐ ํ์ฌ ๋ ธ๋์ ๋ฐ๋ ์๊น์ ์ ์ฉ
- ๋ง์ฝ ๋ฐฉ๋ฌธํ ๋ ธ๋์ธ๋ฐ ํ์ฌ ๋ ธ๋์ ์์ด ๊ฐ์ ๊ฒฝ์ฐ -> ๋ฐ๋ก return False
๊ตฌํ ์ฝ๋
from collections import deque import sys input = sys.stdin.readline def bfs(start, graph, color): q = deque([start]) color[start] = 1 while q: v = q.popleft() for nxt in graph[v]: if color[nxt] == 0: color[nxt] = -color[v] q.append(nxt) elif color[nxt] == color[v]: return False return True def is_bipartite(v, graph): color = [0] * (v + 1) for i in range(1, v+1): if color[i] == 0: if not bfs(i, graph, color): return False return True k = int(input()) for _ in range(k): v, e = map(int, input().split()) graph = [[] for _ in range(v+1)] for _ in range(e): a, b = map(int, input().split()) graph[a].append(b) graph[b].append(a) print("YES" if is_bipartite(v, graph) else "NO")'๐ปProgramming > Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] ์ต๋จ๊ฒฝ๋ก(๊ณจ๋4) (0) 2025.10.01 [๋ฐฑ์ค] ํ ๋งํ (๊ณจ๋5) (0) 2025.09.09 [๋ฐฑ์ค] ๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ(๊ณจ๋3) (0) 2025.09.08 [๋ฐฑ์ค] ํธ๋ฆฌ์ ์ง๋ฆ(๊ณจ๋4) (0) 2025.09.02 [ํ๋ก๊ทธ๋๋จธ์ค] N์ผ๋ก ํํ(level3) (0) 2025.08.29