-
Notifications
You must be signed in to change notification settings - Fork 46
/
go.go
73 lines (63 loc) · 1.29 KB
/
go.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"fmt"
"io"
"os"
"time"
)
type route struct {
to int32
cost int32
}
type node struct {
neighbours []route
}
func readPlaces() ([]node, int) {
f, err := os.Open("agraph")
if err != nil {
panic(err)
}
defer f.Close()
var numNodes int
if _, err := fmt.Fscanln(f, &numNodes); err != nil {
panic(err)
}
nodes := make([]node, numNodes)
for i := range nodes {
nodes[i].neighbours = make([]route, 0, numNodes/2)
}
for {
var node int32
var r route
switch _, err := fmt.Fscanln(f, &node, &r.to, &r.cost); {
case err == io.EOF:
return nodes, numNodes
case err != nil:
panic(err)
}
nodes[node].neighbours = append(nodes[node].neighbours, r)
}
}
func getLongestPath(nodes []node, nodeID int32, visited []bool) int32 {
visited[nodeID] = true
var max int32
for _, neighbour := range nodes[nodeID].neighbours {
if visited[neighbour.to] {
continue
}
dist := neighbour.cost + getLongestPath(nodes, neighbour.to, visited)
if dist > max {
max = dist
}
}
visited[nodeID] = false
return max
}
func main() {
nodes, nNodes := readPlaces()
visited := make([]bool, nNodes)
start := time.Now()
len := getLongestPath(nodes, 0, visited)
duration := time.Since(start).Nanoseconds() / 1000000
fmt.Printf("%v LANGUAGE Go %v\n", len, duration)
}