-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathalgo.go
52 lines (44 loc) · 1.23 KB
/
algo.go
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
package hungarianAlgorithm
// Returns the solution as an array `a` such that each row `i` is matched to
// column `a[i]`
func Solve(costs [][]int) ([]int, error) {
// Validate the input
if err := validate(costs); err != nil {
return []int{}, err
}
n := len(costs)
label := makeLabel(n, costs) // labels on the row and columns
match := makeMatching(n) // matching using tight edges
label.initialize()
match.initialize(label.isTight)
// loop until the matching is perfect
for p, r := match.isPerfect(); !p; p, r = match.isPerfect() {
e := label.initializeSlacks(r) // initializes the min slacks to r
t := makeTree(n, r, e) // alternating tree rooted at r
// loop until the matching is augmented
for true {
var j int // new column index in the tree
// Extend the tree
if b, k := t.extend(); b {
j = k
} else {
u, v := t.indices()
e := label.update(u, v)
t.addTightEdges(e)
_, j = t.extend()
}
if b, i := match.isMatched(j); b {
// Add the edge (i, j) to the tree
t.addEdge(i, j)
e := label.updateSlacks(i)
t.addTightEdges(e)
} else {
// Augment the matching
path := t.pathToRoot(j)
match.augment(path)
break
}
}
}
return match.format(), nil
}