FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
competitive-programming/Graph/binarylifting.cpp at master · kothariji/competitive-programming · GitHub
kothariji
/
competitive-programming
Public
Notifications
You must be signed in to change notification settings
Fork
500
Star
704
Code
Issues
1
Pull requests
2
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
competitive-programming
/
Graph
/
binarylifting.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
77 lines (67 loc) · 1.36 KB
Breadcrumbs
competitive-programming
/
Graph
/
binarylifting.cpp
Copy path
File metadata and controls
77 lines (67 loc) · 1.36 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
//
author : Avishkar A. Hande
#
include
<
bits/stdc++.h
>
#
define
ll
long
long
using
namespace
std
;
const
int
maxS =
1e5
+
10
;
vector<ll> adj[maxS];
ll
LOG
;
int
timer;
vector<
int
> tin, tout;
vector<vector<
int
>> up;
/*
Binary Lifting is mostly used to find Lowest Common Ancestor
as it reduces the time complexity to log(n);
*/
void
dfs
(
int
v,
int
p)
{
tin[v] = ++timer;
up[v][
0
] = p;
for
(
int
i =
1
; i <=
LOG
; ++i)
up[v][i] = up[up[v][i-
1
]][i-
1
];
for
(
int
u : adj[v]) {
if
(u != p)
dfs
(u, v);
}
tout[v] = ++timer;
}
bool
is_ancestor
(
int
u,
int
v)
{
return
tin[u] <= tin[v] && tout[u] >= tout[v];
}
int
lca
(
int
u,
int
v)
{
if
(
is_ancestor
(u, v))
return
u;
if
(
is_ancestor
(v, u))
return
v;
for
(
int
i =
LOG
; i >=
0
; --i) {
if
(!
is_ancestor
(up[u][i], v))
u = up[u][i];
}
return
up[u][
0
];
}
void
preprocess
(
int
root,
int
n) {
tin.
resize
(n);
tout.
resize
(n);
timer =
0
;
LOG
=
ceil
(
log2
(n)) +
1
;
up.
assign
(n+
1
, vector<
int
>(
LOG
+
1
));
dfs
(root, root);
}
int
main
()
{
ll node, queries;
cin >> node >> queries;
for
(
int
i =
0
; i < node-
1
; i++){
ll u, v;
cin >> u >> v;
adj[u].
push_back
(v);
adj[v].
push_back
(u);
}
preprocess
(
1
, node);
while
(queries--){
ll a, b;
cin >> a >> b;
cout <<
lca
(a, b) << endl;
}
}
Back
|
FazBrowse Home
|
New Git URL