-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathjscache.js
64 lines (59 loc) · 1.67 KB
/
jscache.js
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
var fs = require('fs');
var nodes = [], visited = [];
var visitCache = {};
function readPlaces() {
var lines = fs.readFileSync('agraph','utf8').split('\n');
var numnodes = lines[0]|0;
for(var i=0;i<numnodes;i++) {
nodes[i] = [];
visited[i] = false;
}
for(i=1;i<lines.length;i++) {
var line = lines[i].split(' ');
nodes[line[0]|0].push({dst: line[1]|0, cost: line[2]|0});
}
}
function getLongestPath(nodes, nodeid, visited) {
visited[nodeid] = true;
var neighbours = nodes[nodeid];
var max = 0
for(var i=0;i<neighbours.length;i++) {
if (!visited[neighbours[i].dst]) {
var dist = neighbours[i].cost + getLongestPath(nodes, neighbours[i].dst, visited);
if (dist > max) {
max = dist
}
}
}
visited[nodeid] = false;
return max;
}
function getLongestPathCached(nodes, nodeid, visited, depth) {
var idx;
visited |= 1 << nodeid;
idx = (visited * 32) + nodeid;
if (visitCache[idx]) {
return visitCache[idx];
}
var neighbours = nodes[nodeid];
var max = 0
for(var i=0;i<neighbours.length;i++) {
if (!(visited & (1 << neighbours[i].dst))) {
var dist = neighbours[i].cost + getLongestPathCached(nodes, neighbours[i].dst, visited, depth+1);
if (dist > max) {
max = dist
}
}
}
visitCache[idx] = max;
return max;
}
readPlaces();
var start = Date.now();
var length;
if (nodes.length < 32) {
length = getLongestPathCached(nodes, 0, 0, 0);
} else {
length = getLongestPath(nodes, 0, visited);
}
console.log(length+' LANGUAGE JavascriptWithCacheAlg '+(Date.now() - start));