문제) 백준 - DFS - 트리
https://www.acmicpc.net/problem/4803
4803번: 트리
입력으로 주어진 그래프에 트리가 없다면 "No trees."를, 한 개라면 "There is one tree."를, T개(T > 1)라면 "A forest of T trees."를 테스트 케이스 번호와 함께 출력한다.
www.acmicpc.net
1번 노드부터 탐색하면서 트리의 개수를 계산합니다. 그래프에서 노드의 개수와 간선의 개수를 계산하여 cntEdge(i) / 2 == cntNode(i) - 1을 통해 트리 여부를 판별합니다.
C++ 소스코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Node | |
int cntNode(int now){ | |
int cnt = 1; | |
visited[now] = true; | |
for(int next: graph[now]) | |
if(!visited[next]) | |
cnt += cntNode(next); | |
return cnt; | |
} | |
// Edge | |
int cntEdge(int now){ | |
int cnt = graph[now].size(); | |
finished[now] = true; | |
for(int next: graph[now]) | |
if(!finished[next]) | |
cnt += cntEdge(next); | |
return cnt; | |
} |
Full Code)
https://github.com/Chocochip101/BOJ_Solution/blob/main/Solution/4803_%ED%8A%B8%EB%A6%AC.cpp
GitHub - Chocochip101/BOJ_Solution: BOJ Solutions
BOJ Solutions. Contribute to Chocochip101/BOJ_Solution development by creating an account on GitHub.
github.com
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 1145번 - 적어도 대부분의 배수 (C++) 문제 및 풀이 (0) | 2022.02.14 |
---|---|
[백준] 1633번 - 최고의 팀 만들기 (C++) 문제 및 풀이 (0) | 2022.02.12 |
[백준] 3184번 - 양 (C++) 문제 및 풀이 (0) | 2022.02.12 |
[백준] 1032번 - 명령 프롬프트 (C++) 문제 및 풀이 (0) | 2022.02.12 |
[백준] 19238번 - 스타트 택시 (C++) 문제 및 풀이 (0) | 2022.02.10 |
댓글