File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
var pathExistenceQueries = function(n, nums, maxDiff, queries) {
2+
const sortedQueries = queries;
3+
const sortedIndices = Array.from({ length: n }, (_, i) => i);
4+
const position = Array(n).fill(0);
5+
const values = Array(n).fill(0);
6+
7+
sortedIndices.sort((a, b) => nums[a] - nums[b]);
8+
9+
for (let i = 0; i < n; ++i) {
10+
position[sortedIndices[i]] = i;
11+
values[i] = nums[sortedIndices[i]];
12+
}
13+
14+
const reachableIndex = Array(n).fill(0);
15+
let j = 0;
16+
for (let i = 0; i < n; ++i) {
17+
if (j < i) j = i;
18+
while (j + 1 < n && values[j + 1] - values[i] <= maxDiff) ++j;
19+
reachableIndex[i] = j;
20+
}
21+
22+
let maxLog = 1;
23+
while ((1 << maxLog) < n) ++maxLog;
24+
25+
const upTable = Array.from({ length: maxLog }, () => Array(n).fill(0));
26+
upTable[0] = reachableIndex.slice();
27+
28+
for (let k = 1; k < maxLog; ++k) {
29+
for (let i = 0; i < n; ++i) {
30+
upTable[k][i] = upTable[k - 1][upTable[k - 1][i]];
31+
}
32+
}
33+
34+
const results = [];
35+
36+
for (const query of queries) {
37+
let [start, end] = query;
38+
if (start === end) {
39+
results.push(0);
40+
continue;
41+
}
42+
43+
let startPos = position[start], endPos = position[end];
44+
if (startPos > endPos) [startPos, endPos] = [endPos, startPos];
45+
46+
if (Math.abs(nums[start] - nums[end]) <= maxDiff) {
47+
results.push(1);
48+
continue;
49+
}
50+
51+
if (reachableIndex[startPos] < endPos) {
52+
let current = startPos, jumpCount = 0;
53+
for (let k = maxLog - 1; k >= 0; --k) {
54+
if (upTable[k][current] < endPos) {
55+
if (upTable[k][current] === current) break;
56+
current = upTable[k][current];
57+
jumpCount += 1 << k;
58+
}
59+
}
60+
if (reachableIndex[current] >= endPos) results.push(jumpCount + 1);
61+
else results.push(-1);
62+
} else {
63+
results.push(1);
64+
}
65+
}
66+
67+
return results;
68+
};

0 commit comments

Comments
 (0)