using
System;
using
System.Collections.Generic;
public
class
GFG {
static
int
N = 100001;
static
int
M = (
int
) Math.Log(N) + 1;
public
class
pair {
public
int
first, second;
public
pair(
int
first,
int
second) {
this
.first = first;
this
.second = second;
}
}
static
int
[,] anc =
new
int
[N,M];
static
int
[,] val =
new
int
[N,M];
static
int
[] depth =
new
int
[N];
static
void
build(List<pair> []tree,
int
x,
int
p,
int
w,
int
d) {
anc[x,0] = p;
val[x,0] = w;
depth[x] = d;
for
(
int
i = 1; i < M; i++) {
anc[x,i] = anc[anc[x,i - 1],i - 1];
val[x,i] = val[anc[x,i - 1],i - 1] + val[x,i - 1];
}
foreach
(pair i
in
tree[x]) {
if
(i.first != p) {
build(tree, i.first, x, i.second, d + 1);
}
}
}
static
int
findMaxPath(
int
x,
int
y) {
if
(x == y)
return
1;
int
l = 0, r = 0;
if
(depth[x] != depth[y]) {
int
dif = Math.Abs(depth[x] - depth[y]);
if
(depth[x] > depth[y]) {
int
t = x;
x = y;
y = t;
}
for
(
int
i = 0; i < M; i++) {
if
(((1L << i) & (dif)) != 0) {
r += val[y,i];
y = anc[y,i];
}
}
}
if
(x == y)
return
r + 1;
for
(
int
i = M - 1; i >= 0; i--) {
if
(anc[x,i] != anc[y,i]) {
l += val[x,i];
r += val[y,i];
x = anc[x,i];
y = anc[y,i];
}
}
l += val[x,0];
r += val[y,0];
return
Math.Max(l, r);
}
public
static
void
Main(String[] args) {
int
N = 7;
List<pair>[] tree =
new
List<pair>[N + 1];
for
(
int
i = 0; i < tree.Length; i++)
tree[i] =
new
List<pair>();
tree[1].Add(
new
pair(2, 2));
tree[2].Add(
new
pair(1, 2));
tree[1].Add(
new
pair(3, 3));
tree[2].Add(
new
pair(1, 3));
tree[3].Add(
new
pair(4, 4));
tree[4].Add(
new
pair(3, 4));
tree[4].Add(
new
pair(6, 5));
tree[6].Add(
new
pair(4, 5));
tree[3].Add(
new
pair(5, 7));
tree[5].Add(
new
pair(3, 7));
tree[5].Add(
new
pair(7, 6));
tree[7].Add(
new
pair(5, 6));
build(tree, 1, 0, 0, 0);
int
u = 6;
int
v = 5;
Console.Write(findMaxPath(u, v));
}
}