File tree 1 file changed +58
-0
lines changed
solution/3500-3599/3534.Path Existence Queries in a Graph II
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ vector<int > pathExistenceQueries (int n,
4
+ vector<int >& nums,
5
+ int maxDiff,
6
+ vector<vector<int >>& queries) {
7
+ vector<pair<int ,int >> A (n);
8
+ for (int i=0 ;i<n;i++) A[i]={nums[i],i};
9
+ sort (A.begin (),A.end ());
10
+
11
+ vector<int > pos (n);
12
+ for (int i=0 ;i<n;i++) pos[A[i].second ]=i;
13
+
14
+ vector<int > R (n);
15
+ int r = 0 ;
16
+ for (int l=0 ; l<n; l++) {
17
+ while (r+1 <n && A[r+1 ].first - A[l].first <= maxDiff) r++;
18
+ R[l] = r;
19
+ }
20
+
21
+ int LOG = 0 ;
22
+ while ((1 <<LOG) <= n) LOG++;
23
+ vector<vector<int >> jump (LOG, vector<int >(n));
24
+ for (int i=0 ;i<n;i++) jump[0 ][i]=R[i];
25
+ for (int k=1 ;k<LOG;k++){
26
+ for (int i=0 ;i<n;i++){
27
+ jump[k][i] = jump[k-1 ][ jump[k-1 ][i] ];
28
+ }
29
+ }
30
+
31
+ auto minHops = [&](int p, int q)->int {
32
+ if (p>q) return INT_MAX/2 ;
33
+ if (p==q) return 0 ;
34
+ int hops = 0 ;
35
+ int cur = p;
36
+ for (int k=LOG-1 ;k>=0 ;k--){
37
+ int nxt = jump[k][cur];
38
+ if (nxt < q) {
39
+ hops += (1 <<k);
40
+ cur = nxt;
41
+ }
42
+ }
43
+ if (R[cur] < q) return INT_MAX/2 ;
44
+ return hops+1 ;
45
+ };
46
+
47
+ vector<int > ans;
48
+ ans.reserve (queries.size ());
49
+ for (auto &qr: queries){
50
+ int u=qr[0 ], v=qr[1 ];
51
+ int pu=pos[u], pv=pos[v];
52
+ if (pu>pv) swap (pu,pv);
53
+ int h = minHops (pu,pv);
54
+ ans.push_back (h >= INT_MAX/2 ? -1 : h);
55
+ }
56
+ return ans;
57
+ }
58
+ };
You can’t perform that action at this time.
0 commit comments