Skip to content

Commit fa976c7

Browse files
committed
Solve LCA
1 parent 4f8270c commit fa976c7

File tree

2 files changed

+27
-41
lines changed

2 files changed

+27
-41
lines changed

LCA.cpp

+27-41
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,39 @@
1-
#include<bits/stdc++.h>
1+
#include <bits/stdc++.h>
2+
23
using namespace std;
3-
#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)
4-
#define FORD(i,a,b) for(int i = (b); i >= (a); --i)
5-
#define TRAV(x,T) for(auto& (x): (T))
6-
#define ALL(T) T.begin(), T.end()
7-
#define TAB(T,a,b) (T)+a, (T)+((b)+1)
8-
#define VAR(x) #x<<" = "<<x<<" "
9-
#define sz(x) (int)(x).size()
10-
#define nwd __gcd
11-
#define pb push_back
12-
#define st first
13-
#define nd second
14-
#define lc (v<<1)
15-
#define rc (v<<1|1)
16-
typedef long long ll;
17-
typedef long double ld;
18-
typedef pair<int, int> pii;
19-
typedef pair<ll, ll> pll;
20-
typedef vector<int> vi;
21-
#define deb if(0)
4+
225
const int N = 1e6, NT = N + 2;
236
const int LOG = 20; // log n
247

25-
vi V[NT];
8+
vector<int> V[NT];
269
int anc[NT][LOG + 1], pre[NT], post[NT], idx;
2710

2811
void ancestors(int v, int p) {
29-
anc[v][0] = p;
30-
FOR(k, 1, LOG) {
31-
anc[v][k] = anc[ anc[v][k - 1] ][k - 1];
32-
}
33-
idx++;
34-
pre[v] = idx;
35-
TRAV(u, V[v]) {
36-
if(u != v) ancestors(u, v);
37-
}
38-
post[v] = idx;
12+
anc[v][0] = p;
13+
for (int k = 1; k <= LOG; k++) {
14+
anc[v][k] = anc[anc[v][k - 1]][k - 1];
15+
}
16+
idx++;
17+
pre[v] = idx;
18+
for (const int &u : V[v]) {
19+
if (u != v)
20+
ancestors(u, v);
21+
}
22+
post[v] = idx;
3923
}
4024

41-
bool przodek(int a, int b) { // czy a jest przodkiem b
42-
return pre[a] <= pre[b] and pre[b] <= post[a];
25+
bool parent(int a, int b) { // czy a jest przodkiem b
26+
return pre[a] <= pre[b] and pre[b] <= post[a];
4327
}
4428

4529
int LCA(int a, int b) {
46-
if(przodek(a, b)) return a;
47-
if(przodek(b, a)) return b;
48-
FORD(k, 0, LOG) {
49-
if(!przodek(anc[a][k], b))
50-
a = anc[a][k];
51-
}
52-
return anc[a][0];
53-
}
30+
if (parent(a, b))
31+
return a;
32+
if (parent(b, a))
33+
return b;
34+
for (int k = LOG; k >= 0; k--) {
35+
if (!parent(anc[a][k], b))
36+
a = anc[a][k];
37+
}
38+
return anc[a][0];
39+
}
File renamed without changes.

0 commit comments

Comments
 (0)