-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3534.js
68 lines (56 loc) · 2.18 KB
/
3534.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
var pathExistenceQueries = function(n, nums, maxDiff, queries) {
const sortedQueries = queries;
const sortedIndices = Array.from({ length: n }, (_, i) => i);
const position = Array(n).fill(0);
const values = Array(n).fill(0);
sortedIndices.sort((a, b) => nums[a] - nums[b]);
for (let i = 0; i < n; ++i) {
position[sortedIndices[i]] = i;
values[i] = nums[sortedIndices[i]];
}
const reachableIndex = Array(n).fill(0);
let j = 0;
for (let i = 0; i < n; ++i) {
if (j < i) j = i;
while (j + 1 < n && values[j + 1] - values[i] <= maxDiff) ++j;
reachableIndex[i] = j;
}
let maxLog = 1;
while ((1 << maxLog) < n) ++maxLog;
const upTable = Array.from({ length: maxLog }, () => Array(n).fill(0));
upTable[0] = reachableIndex.slice();
for (let k = 1; k < maxLog; ++k) {
for (let i = 0; i < n; ++i) {
upTable[k][i] = upTable[k - 1][upTable[k - 1][i]];
}
}
const results = [];
for (const query of queries) {
let [start, end] = query;
if (start === end) {
results.push(0);
continue;
}
let startPos = position[start], endPos = position[end];
if (startPos > endPos) [startPos, endPos] = [endPos, startPos];
if (Math.abs(nums[start] - nums[end]) <= maxDiff) {
results.push(1);
continue;
}
if (reachableIndex[startPos] < endPos) {
let current = startPos, jumpCount = 0;
for (let k = maxLog - 1; k >= 0; --k) {
if (upTable[k][current] < endPos) {
if (upTable[k][current] === current) break;
current = upTable[k][current];
jumpCount += 1 << k;
}
}
if (reachableIndex[current] >= endPos) results.push(jumpCount + 1);
else results.push(-1);
} else {
results.push(1);
}
}
return results;
};