forked from SR-Sunny-Raj/Hacktoberfest2021-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistance_Queries.cpp
94 lines (93 loc) · 1.95 KB
/
Distance_Queries.cpp
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Problem Link: https://cses.fi/problemset/task/1135/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define mod 10000000000000007
#define FOR(i,x) for(ll i = 0; i < x; i++)
#define For(i,x,y) for(ll i = x; i <= y; i++)
#define rep(i,x,y) for(int i = x; i >= y; i--)
#define vint vector<int>
#define vl vector<long>
#define vll vector<long long>
#define um unordered_map
#define pb push_back
#define pll pair<ll,ll>
#define mone cout<<-1<<"\n"
#define yess cout<<"YES\n"
#define noo cout<<"NO\n"
#define nl cout<<"\n"
#define all(x) x.begin(),x.end()
#define oset tree <int, null_type , less , rb_tree_tag, tree_order_statistics_node_update>
#define INF 1000000000000000000
const ll mx = 2*1e5;
const ll logofn = log2(mx);
void dfs(vector<ll> v[], vector<vector<ll>> &par, ll n, ll p, vector<ll> &lvl)
{
lvl[n] = lvl[p]+1;
par[n][0] = p;
For(i,1,logofn)
par[n][i] = par[par[n][i-1]][i-1];
FOR(i,v[n].size())
{
ll y = v[n][i];
if(y != p)
dfs(v,par,y,n,lvl);
}
}
ll find_lca(vector<ll> v[], vector<vector<ll>> &par, ll a, ll b, vector<ll> &lvl)
{
if(lvl[a] < lvl[b])
swap(a,b);
ll d = lvl[a]-lvl[b];
while(d > 0)
{
ll z = log2(d);
a = par[a][z];
d -= (1<<z);
}
if(a == b)
return a;
rep(i,logofn,0)
{
if(par[a][i] != par[b][i])
{
a = par[a][i];
b = par[b][i];
}
}
return par[a][0];
}
int main()
{
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll t;
t=1;
while(t--)
{
ll n,q;
cin>>n>>q;
vector<ll> v[n+1];
FOR(i,n-1)
{
ll a,b;
cin>>a>>b;
v[a].pb(b);
v[b].pb(a);
}
vector<vector<ll>> par(n+1,vector<ll>(logofn+1,0));
vector<ll> lvl(n+1,0);
dfs(v,par,1,0,lvl);
while(q--)
{
ll a,b;
cin>>a>>b;
ll z = find_lca(v,par,a,b,lvl);
cout<<lvl[a]+lvl[b]-2*lvl[z]<<"\n";
}
}
}