반응형
문제
https://www.acmicpc.net/problem/1967
1967번: 트리의 지름
파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연
www.acmicpc.net
풀이
https://dev-mandos.tistory.com/291
[BOJ] 백준 1167 트리의 지름 (Swift)
문제 https://www.acmicpc.net/problem/1167 1167번: 트리의 지름 트리가 입력으로 주어진다. 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2 ≤ V ≤ 100,000)둘째 줄부터 V개의 줄에 걸쳐 간선의 정
dev-mandos.tistory.com
위 문제와 입력만 다르고 완전 똑같은 문제였습니다.
소스코드
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
let n = Int(readLine()!)! | |
var graph = [[(Int, Int)]](repeating: [], count: n + 1) | |
var visited = [Bool](repeating: false, count: n + 1) | |
for _ in 0..<n - 1{ | |
let input = readLine()!.split(separator: " ").map { Int($0)! } | |
let a = input[0], b = input[1], cost = input[2] | |
graph[a].append((b, cost)) | |
graph[b].append((a, cost)) | |
} | |
var endNode: (node: Int, cost: Int) = (node: 0, cost: 0) | |
func dfs(node: Int, depth: Int) { | |
visited[node] = true | |
if depth > endNode.cost { | |
endNode = (node, depth) | |
} | |
for (nextNode, distance) in graph[node] { | |
if !visited[nextNode] { | |
visited[nextNode] = true | |
dfs(node: nextNode, depth: depth + distance) | |
visited[nextNode] = false | |
} | |
} | |
} | |
dfs(node: 1, depth: 0) | |
visited = [Bool](repeating: false, count: n + 1) | |
dfs(node: endNode.node, depth: 0) | |
print(endNode.cost) |
후기
이전 문제를 풀었기에 쉽게 풀 수 있었던 문제였습니다.
반응형
'PS > 백준' 카테고리의 다른 글
[BOJ] 백준 4803 트리 (Swift) (0) | 2023.05.16 |
---|---|
[BOJ] 백준 1991 트리 순회 (Swift) (0) | 2023.05.15 |
[BOJ] 백준 1167 트리의 지름 (Swift) (0) | 2023.05.15 |
[BOJ] 백준 11725 트리의 부모 찾기 (Swift) (0) | 2023.05.15 |
[BOJ] 백준 11780 플로이드 2 (Swift) (0) | 2023.05.15 |