-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1572A-Book.js
81 lines (71 loc) · 1.64 KB
/
1572A-Book.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const readline = require("readline");
const os = require("os");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let lineNum = 0, consumed = 0, lineNo = 0
let input = []
let res = []
let out = []
rl.on("line", (line) => {
input.push(line)
if (input.length === 2) {
lineNum = +input[1]
}
if(input.length > 2) {
consumed++
input.pop()
const tmp = line.split(' ').map(e => +e)
lineNo++
if(tmp.length > 1) {
for(let j = 1; j < tmp.length; j++) {
res.push([tmp[j], lineNo])
}
}
if(consumed === lineNum) {
const ans = solution(res, lineNum)
out.push(ans === -1 ? -1 : ans)
input.length = 1
consumed = 0
lineNo = 0
res = []
}
}
});
rl.on("close", () => {
let str = ''
for(const e of out) str += e + os.EOL
console.log(str)
});
function solution(arr, n) {
const graph = {}, inDegree = Array(n + 1).fill(0)
for(const [u, v] of arr) {
if(graph[u] == null) graph[u] = []
graph[u].push(v)
inDegree[v]++
}
const q = [], visited = new Set(), times = Array(n + 1).fill(0)
for(let i = 1; i <= n; i++) {
if(inDegree[i] === 0) {
q.push(i)
visited.add(i)
}
times[i] = 1
}
while(q.length) {
const cur = q.pop()
for(const next of (graph[cur] || [])) {
inDegree[next]--
if(cur < next) times[next] = Math.max(times[cur], times[next])
else times[next] = Math.max(times[next], times[cur] + 1)
if(inDegree[next] === 0) {
q.push(next)
visited.add(next)
}
}
}
if (visited.size === n) {
return Math.max(...times)
} else return -1
}