Skip to content
CatBus

Tag: trees

All the articles with the tag "trees".

BOJ4803GOLD 4
for i in range(1, n + 1):
    if not visited[i]:
        nodes = set()
        edges = set()

        # 사이클 확인
        if not dfs(i, 0, nodes, edges):
            continue

        # 사이클이 없고, 간선의 수가 노드의 수 - 1이면 트리
        if len(edges) == len(nodes) - 1:
            tree_count += 1
  • 방문하지 않은 각 연결 요소에 대해 DFS 수행
  • 사이클이 없고 간선 수 = 정점 수 - 1이면 트리로 카운트
if tree_count == 0:
    print(f"Case {case_num}: No trees.")
elif tree_count == 1:
    print(f"Case {case_num}: There is one tree.")
else:
    print(f"Case {case_num}: A forest of {tree_count} trees.")

트리

백준 4803번 '트리' (골드 4) 문제 풀이. graph theory, data structures, graph traversal 로 접근했다.

2025.03.25·9분·graph theory