-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1504번.swift
63 lines (58 loc) · 1.76 KB
/
1504번.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 출처 : 백준 특정한 최단 경로
// https://www.acmicpc.net/problem/1504
// 풀이 : hogumachu
let input = readLine()!.split(separator: " ").map{Int(String($0))!}
let N = input[0], E = input[1]
var graph: [[(Int, Int)]] = Array(repeating: [], count: N + 1)
var weights = Array(repeating: 999_999_999_999, count: N + 1)
let saveWeights = weights
var visited = Array(repeating: false, count: N + 1)
let saveVisited = visited
var result: [Int] = []
for _ in 0..<E {
let secondInput = readLine()!.split(separator: " ").map{Int(String($0))!}
graph[secondInput[0]].append((secondInput[1],secondInput[2]))
graph[secondInput[1]].append((secondInput[0],secondInput[2]))
}
let thirdInput = readLine()!.split(separator: " ").map{Int(String($0))!}
let v1 = thirdInput[0], v2 = thirdInput[1]
result.append(sol(v1,v2))
result.append(sol(v2, v1))
print(result.min()! == 999_999_999_999 ? -1 : result.min()!)
func sol(_ first: Int, _ second: Int) -> Int {
weights = saveWeights
visited = saveVisited
weights[1] = 0
visit(1, first)
let firstWeight = weights[first]
weights = saveWeights
visited = saveVisited
weights[first] = firstWeight
visit(first, second)
let secondWeight = weights[second]
weights = saveWeights
visited = saveVisited
weights[second] = secondWeight
visit(second, N)
return weights[N]
}
func visit(_ now: Int, _ to: Int) {
if now == to {
return
}
visited[now] = true
for i in graph[now] {
weights[i.0] = min(weights[i.0], weights[now] + i.1)
}
let next = weights.enumerated()
.filter({
!visited[$0.offset]
})
.min(by: {
$0.element < $1.element
})?
.offset
if next != nil {
visit(next!, to)
}
}