2025-10-26 17:10:15 +09:00

66 lines
1.9 KiB
Swift

if let n = Int(readLine() ?? ""),
let m = Int(readLine() ?? "")
{
var graph: [[(v: Int, w: Int)]] = Array(repeating: [], count: n+1)
for _ in 0..<m {
if let input = readLine(),
let nums = input.split(separator: " ").compactMap({Int($0)}) as? [Int],
nums.count == 3
{
let u = nums[0]
let v = nums[1]
let w = nums[2]
graph[u].append((v: v, w: w))
}
}
if let input = readLine(),
let start_end = input.split(separator: " ").compactMap({Int($0)}) as? [Int],
start_end.count == 2
{
let start = start_end[0]
let end = start_end[1]
var prev = Array(repeating: 0, count: n+1)
var qu: [(now: Int, distance: Int)] = []
var distance: [Int] = Array(repeating: Int.max, count: n+1)
qu.append((now: start, distance: 0))
distance[start] = 0
while !qu.isEmpty {
let current = qu.removeFirst()
if distance[current.now] < current.distance {
continue
}
for next in graph[current.now] {
if distance[next.v] > distance[current.now] + next.w {
distance[next.v] = distance[current.now] + next.w
prev[next.v] = current.now
qu.append((now: next.v, distance: distance[next.v]))
}
}
}
var path: [Int] = []
path.append(end)
while true {
let temp = path[path.count-1]
if prev[temp] == 0 {
break
}
path.append(prev[temp])
}
path.reverse()
print(distance[end])
print(path.count)
print(path.map({String($0)}).joined(separator: " "))
}
}