84 lines
2.4 KiB
Swift
84 lines
2.4 KiB
Swift
let inf: Int = 987654321
|
|
|
|
func dijk(from start: Int,_ node: [[(Int,Int)]], _ n: Int) -> [Int] {
|
|
var dist: [Int] = Array(repeating: inf, count: n+1)
|
|
dist[start] = 0
|
|
var qu = [(Int, Int)]()
|
|
qu.append((start, 0))
|
|
|
|
while !qu.isEmpty {
|
|
if let (now, weight) = qu.first {
|
|
qu.removeFirst()
|
|
|
|
if dist[now] < weight {
|
|
continue
|
|
}
|
|
|
|
for tup in node[now] {
|
|
if dist[tup.0] > tup.1 + weight {
|
|
dist[tup.0] = tup.1 + weight
|
|
qu.append((tup.0, dist[tup.0]))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return dist
|
|
}
|
|
|
|
if let input1 = readLine(),
|
|
let temp1 = input1.split(separator: " ").compactMap({Int($0)}) as? [Int],
|
|
let N: Int = temp1.first, let E: Int = temp1.last
|
|
{
|
|
var node: [[(Int, Int)]] = Array(repeating: [(Int, Int)](), count: N+1)
|
|
|
|
for _ in 0..<E {
|
|
if let input2 = readLine(),
|
|
let temp2 = input2.split(separator: " ").compactMap({Int($0)}) as? [Int],
|
|
temp2.count == 3
|
|
{
|
|
let u: Int = temp2[0]
|
|
let v: Int = temp2[1]
|
|
let c: Int = temp2[2]
|
|
|
|
node[u].append((v,c))
|
|
node[v].append((u,c))
|
|
}
|
|
}
|
|
|
|
if let input3 = readLine(),
|
|
let temp3 = input3.split(separator: " ").compactMap({Int($0)}) as? [Int],
|
|
let v1: Int = temp3.first, let v2: Int = temp3.last
|
|
{
|
|
let Dist_from1: [Int] = dijk(from: 1, node, N)
|
|
let Dist_fromV1: [Int] = dijk(from: v1, node, N)
|
|
let Dist_fromV2: [Int] = dijk(from: v2, node, N)
|
|
|
|
print(Dist_from1)
|
|
print(Dist_fromV1)
|
|
print(Dist_fromV2)
|
|
|
|
//path1 1->v1->v2->N
|
|
var path1: Int = -1
|
|
if Dist_from1[v1] < inf && Dist_fromV1[v2] < inf && Dist_fromV2[N] < inf {
|
|
path1 = Dist_from1[v1] + Dist_fromV1[v2] + Dist_fromV2[N]
|
|
}
|
|
|
|
//path2 1->v2->v1->N
|
|
var path2: Int = -1
|
|
if Dist_from1[v2] < inf && Dist_fromV2[v1] < inf && Dist_fromV1[N] < inf {
|
|
path2 = Dist_from1[v2] + Dist_fromV2[v1] + Dist_fromV1[N]
|
|
}
|
|
|
|
if path1 == -1 && path2 == -1 {
|
|
print(-1)
|
|
}
|
|
else if path1 == -1 || path2 == -1 {
|
|
print(max(path1, path2))
|
|
}
|
|
else {
|
|
print(min(path1, path2))
|
|
}
|
|
}
|
|
}
|