[BaekJoon] 10216λ² : Count Circle Groups
Updated:
10216λ² : Count Circle Groups
μ κ΅°μ μ§μμ BFS λ‘ νμνλ©΄μ ν΅μ μ΄ λλ κ²½μ° μ°κ²°ν΄ μ£Όλ©΄ λλ€.
λ°©λ¬Έ νμ§ μμ μ§μμ μμμΌλ‘ BFS λ₯Ό μννκ³ , BFS λ₯Ό μν ν νμκ° κ·Έλ£Ήμ κ°μκ° λλ€.
union-find λ₯Ό μ¬μ©νλ©΄ BFS λ³΄λ€ μκ°μ λ¨μΆ ν μ μλ€.
νμ§λ§.. μ΄λ»κ² μ μ©μ μμΌμΌ ν μ§ μμ§ λͺ¨λ₯΄κ² λ€.
볡μ΅μ ν λλ union-find λ₯Ό μ¬μ©ν΄ νμ΄λ΄μΌκ² λ€.
[21.03.11] 볡μ΅
union-find λ₯Ό μ μ©ν΄ νμ΄λ³΄μλ€. κΈ°μ‘΄μ μ½λλ 14000ms κ° κ±Έλ Έλ λ°λ©΄ μ§κΈμ 2100ms κ° μμλλ€.
μ²μμ κ°λ₯ν λͺ¨λ κ°μ μ λ§λ λ€ κ·Έ κ°μ μ μ 보λ₯Ό κ°μ§κ³ MST λ₯Ό λ§λλ λ°©μμΌλ‘ νλ€.
νμ§λ§ μκ°μ΄κ³Όκ° λ°μνκ³ , κ°λ₯ν λͺ¨λ κ°μ μ λ§λ€μ§ μκ³ λ Έλ μ 보λ§μ κ°μ§κ³ union-find λ₯Ό ν΄μΌνλ€.
κ·Έλ°λ° κ³μ μκ°ν΄λ³΄λ μ μ΄μ κ°μ μ λ§λ€ μ΄μ κ° μμλ€.
λ Έλμ μ 보λ§μΌλ‘ λ λ Έλκ° μ°κ²°λ μ§ μλ μ§λ₯Ό μ ν μ μμκΈ° λλ¬Έμ΄λ€.
λ Έλ μ 보λ₯Ό x_pos, y_pos, radius λ‘ λλμ΄ μ μ₯νλ λ°©λ²κ³Ό
nodes 리μ€νΈμ ν λ²μ μ μ₯ν λ€ κ°μ Έλ€ μ°λ λ°©λ²μ λ¬΄λ € 5000ms λ μ°¨μ΄κ° λλ€.
[21.03.11] 볡μ΅
import sys
def find_parent(parent, node):
if parent[node] != node:
parent[node] = find_parent(parent, parent[node])
return parent[node]
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
def solution():
answer = node_cnt
parent = [i for i in range(node_cnt)]
for i in range(node_cnt):
for j in range(i + 1, node_cnt):
x_dif = x_pos[i] - x_pos[j]
y_dif = y_pos[i] - y_pos[j]
dist = radius[i] + radius[j]
if (x_dif ** 2) + (y_dif ** 2) <= dist ** 2:
if find_parent(parent, i) != find_parent(parent, j):
union_parent(parent, i, j)
answer -= 1
return answer
if __name__ == "__main__":
testcase = int(input())
for _ in range(testcase):
node_cnt = int(input())
x_pos, y_pos, radius = [], [], []
for _ in range(node_cnt):
x, y, r = map(int, sys.stdin.readline().rsplit())
x_pos.append(x)
y_pos.append(y)
radius.append(r)
print(solution())
import sys
from collections import deque
def BFS(visit, start):
queue = deque([nodes[start]])
visit[start] = True
while queue:
x1, y1, r1 = queue.popleft()
for idx, node in enumerate(nodes):
if not visit[idx]:
x2, y2, r2 = node
dist = (x1 - x2) ** 2 + (y1 - y2) ** 2
if dist <= (r1 + r2) ** 2:
visit[idx] = True
queue.append(node)
def solution():
visit = [False] * node_cnt
BFS_cnt = 0
for idx, node in enumerate(nodes):
if not visit[idx]:
BFS(visit, idx)
BFS_cnt += 1
return BFS_cnt
if __name__ == "__main__":
testcase = int(input())
for _ in range(testcase):
node_cnt = int(input())
nodes = []
for _ in range(node_cnt):
x, y, r = map(int, sys.stdin.readline().rsplit())
nodes.append([x, y, r])
print(solution())
Leave a comment