using
System;
using
System.Collections.Generic;
class
GFG{
private
static
List<List<
int
>> constructTree(
int
n,
int
[,] edges)
{
List<List<
int
> > adjl =
new
List<List<
int
> >();
for
(
int
i = 0; i < n; i++)
{
adjl.Add(
new
List<
int
>());
}
for
(
int
i = 0; i < edges.GetLength(0); i++)
{
int
u = edges[i, 0];
int
v = edges[i, 1];
adjl[u].Add(v);
adjl[v].Add(u);
}
return
adjl;
}
private
static
void
DFS(List<List<
int
> > adjl,
int
[] parent,
int
u,
int
p)
{
parent[u] = p;
foreach
(
int
v
in
adjl[u])
{
if
(v != p)
{
DFS(adjl, parent, v, u);
}
}
}
private
static
int
[] valuesFromChildren(
int
[] parent,
int
[] values)
{
int
[] valuesChildren =
new
int
[parent.Length];
for
(
int
i = 0; i < parent.Length; i++)
{
if
(parent[i] == -1)
continue
;
else
{
int
p = parent[i];
valuesChildren[p] += values[i];
}
}
return
valuesChildren;
}
private
static
int
findSumOfValues(
int
v,
int
[] parent,
int
[] valuesChildren)
{
int
cur_node = v;
int
sum = 0;
while
(cur_node != -1)
{
sum += valuesChildren[cur_node];
cur_node = parent[cur_node];
}
return
sum;
}
public
static
void
Main(
string
[] args)
{
int
n = 8;
int
[, ] edges = { { 0, 1 }, { 0, 2 }, { 0, 3 },
{ 1, 4 }, { 1, 5 }, { 4, 7 },
{ 3, 6 } };
int
v = 7;
int
[] values =
new
int
[] { 1, 2, 3, 0,
0, 4, 3, 6 };
List<List<
int
>> adjl = constructTree(n, edges);
int
[] parent =
new
int
[n];
DFS(adjl, parent, 0, -1);
int
[] valuesChildren = valuesFromChildren(parent,
values);
int
sum = findSumOfValues(v, parent,
valuesChildren);
sum += values[0];
Console.WriteLine(sum);
}
}