using
System;
using
System.Collections.Generic;
class
GfG
{
private
static
int
[,]table;
private
static
int
height;
private
static
List<List<
int
> > Graph;
private
static
int
[]timeIn;
private
static
int
[]timeOut;
private
static
int
time;
private
GfG(
int
n)
{
height = (
int
)Math.Ceiling(Math.Log10(n) / Math.Log10(2));
table =
new
int
[n + 1, height + 1];
Graph =
new
List<List<
int
> >();
for
(
int
i = 0; i <= n; i++)
Graph.Add(
new
List<
int
>());
timeIn =
new
int
[n + 1];
timeOut =
new
int
[n + 1];
time = 0;
}
private
static
void
preprocessing(
int
n)
{
for
(
int
i = 0; i < n + 1; i++)
{
for
(
int
j = 0; j < height + 1; j++)
table[i, j] = -1;
}
}
private
static
void
dfs(
int
s,
int
p)
{
table[s, 0] = p;
timeIn[s] = ++time;
for
(
int
i = 1; i <= height; i++)
table[s, i] = table[table[s, i - 1], i - 1];
foreach
(
int
child
in
Graph[s])
{
if
(child == p)
continue
;
dfs(child, s);
}
timeOut[s] = ++time;
}
private
static
bool
check(
int
u,
int
v)
{
return
timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v];
}
private
static
int
lowestCommonAncestor(
int
U,
int
V)
{
if
(check(U, V))
return
U;
if
(check(V, U))
return
V;
for
(
int
i = height; i >= 0; i--)
{
if
(!check(table[U, i], V))
U = table[U, i];
}
return
table[U, 0];
}
private
static
bool
isPresent(
int
U,
int
V,
int
R)
{
dfs(1, 1);
int
LCA = lowestCommonAncestor(U, V);
int
LCA_1 = lowestCommonAncestor(U, R);
int
LCA_2 = lowestCommonAncestor(V, R);
if
(LCA == R || (LCA_1 == LCA && LCA_2 == R)
|| (LCA_2 == LCA && LCA_1 == R))
{
return
true
;
}
return
false
;
}
public
static
void
Main(String []args)
{
int
n = 6;
GfG obj =
new
GfG(n);
preprocessing(n);
Graph[1].Add(2);
Graph[2].Add(1);
Graph[1].Add(3);
Graph[3].Add(1);
Graph[2].Add(4);
Graph[4].Add(2);
Graph[2].Add(5);
Graph[5].Add(2);
Graph[3].Add(6);
Graph[6].Add(3);
int
U = 4, V = 6, R = 2;
if
(isPresent(U, V, R))
Console.Write(
"Yes"
);
else
Console.Write(
"No"
);
}
}