20251022 baekjoon
This commit is contained in:
parent
5b6e1504d6
commit
0372cacdf7
47
code_study/Baekjoon/swift/1167.swift
Normal file
47
code_study/Baekjoon/swift/1167.swift
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
func findMaxLenNode(start n: Int, of graph: [[(node: Int, dist: Int)]]) -> (node: Int, dist: Int) {
|
||||||
|
var result = (node: n, dist: 0)
|
||||||
|
var visited = Array(repeating: false, count: graph.count+1)
|
||||||
|
var stack: [(node: Int, dist: Int)] = []
|
||||||
|
stack.append(result)
|
||||||
|
visited[n] = true
|
||||||
|
|
||||||
|
while !stack.isEmpty {
|
||||||
|
if let (cur_node, cur_dist) = stack.popLast(){
|
||||||
|
|
||||||
|
if cur_dist > result.dist {
|
||||||
|
result = (node: cur_node, dist: cur_dist)
|
||||||
|
}
|
||||||
|
|
||||||
|
for next in graph[cur_node] {
|
||||||
|
if !visited[next.node] {
|
||||||
|
stack.append((node: next.node, dist: cur_dist + next.dist))
|
||||||
|
visited[next.node] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if let V = Int(readLine() ?? "") {
|
||||||
|
var tree: [[(node: Int, dist: Int)]] = Array(repeating: [], count: V+1)
|
||||||
|
|
||||||
|
for _ in 1...V {
|
||||||
|
if let line = readLine(),
|
||||||
|
let info = line.split(separator: " ").compactMap({Int($0)}) as? [Int]
|
||||||
|
{
|
||||||
|
let u = info[0]
|
||||||
|
var i = 1
|
||||||
|
|
||||||
|
while info[i] != -1 {
|
||||||
|
tree[u].append((node: info[i], dist: info[i+1]))
|
||||||
|
i += 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = findMaxLenNode(start: 1, of: tree).node
|
||||||
|
print(findMaxLenNode(start: start, of: tree).dist)
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user