-
4803번: 트리
입력으로 주어진 그래프에 트리가 없다면 "No trees."를, 한 개라면 "There is one tree."를, T개(T > 1)라면 "A forest of T trees."를 테스트 케이스 번호와 함께 출력한다.
www.acmicpc.net
코드
import sys input = sys.stdin.readline def check(num): visited[num] = True stack = [num] while stack: node = stack.pop(0) for next_node in tree[node]: if tree[node][next_node] == 1: if not visited[next_node]: visited[next_node] = True stack.append(next_node) tree[node][next_node] = 0 tree[next_node][node] = 0 else: return False return True tc = 1 while True: N,M = map(int,input().split()) if N+M == 0: break parent_cnt = [0]*(N+1) tree = [{} for _ in range(N+1)] for _ in range(M): x,y = map(int,input().split()) tree[x][y] = 1 tree[y][x] = 1 cnt = 0 visited = [False]*(N+1) for num in range(1,N+1): if not visited[num]: if check(num): cnt += 1 if cnt == 0: print(f'Case {tc}: No trees.') elif cnt == 1: print(f'Case {tc}: There is one tree.') else: print(f'Case {tc}: A forest of {cnt} trees.') tc += 1
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 9372번 상근이의 여행 (파이썬) (0) 2022.01.06 [백준] 1717번 집합의 표현 (파이썬) (0) 2022.01.06 [백준] 5639번 이진 검색 트리 (파이썬) (0) 2022.01.05 [백준] 2263번 트리의 순회 (파이썬) (0) 2022.01.05 [백준] 1991번 트리 순회 (파이썬) (0) 2022.01.05