using
System;
using
System.Collections.Generic;
public
class
GFG {
static
int
[, ] dp =
new
int
[1000, 2];
static
int
dfs(
int
root,
Dictionary<
int
, List<
int
> > graph,
List<
int
> v,
int
pick,
int
parent)
{
int
ans = 0;
if
(dp[root, pick] != -1) {
return
dp[root, pick];
}
if
(pick == 1) {
ans += v[root];
foreach
(
int
it
in
graph[root])
{
if
(it != parent) {
ans += dfs(it, graph, v, 0, root);
}
}
return
ans;
}
else
{
int
temp = v[root];
foreach
(
int
it
in
graph[root])
{
if
(it != parent) {
temp += dfs(it, graph, v, 0, root);
}
}
for
(
int
it = 0; it < graph[root].Count; it++) {
if
(graph[root][it] != parent) {
ans += dfs(graph[root][it], graph, v, 1,
root);
}
}
ans = Math.Min(ans, temp);
}
dp[root, pick] = ans;
return
ans;
}
static
int
findminSum(
int
[, ] edges, List<
int
> v,
int
N)
{
Dictionary<
int
, List<
int
> > graph
=
new
Dictionary<
int
, List<
int
> >();
for
(
int
i = 0; i < N - 1; i++) {
int
a = edges[i, 1];
int
b = edges[i, 0];
if
(!graph.ContainsKey(a)) {
graph.Add(a,
new
List<
int
>());
}
graph[a].Add(b);
if
(!graph.ContainsKey(b)) {
graph.Add(b,
new
List<
int
>());
}
graph[b].Add(a);
}
for
(
int
i = 0; i < 1000; i++) {
dp[i, 0] = -1;
dp[i, 1] = -1;
}
int
pick = 0;
int
parent = -1;
return
dfs(0, graph, v, pick, parent);
}
static
public
void
Main()
{
int
N = 4;
List<
int
> arr
=
new
List<
int
>(
new
int
[] { 3, 4, 20, 14 });
int
[, ] edges = { { 1, 0 }, { 3, 0 }, { 2, 3 } };
Console.WriteLine(findminSum(edges, arr, N));
int
N2 = 3;
List<
int
> arr2
=
new
List<
int
>(
new
int
[] { 5, 12, 3 });
int
[, ] edges2 = { { 0, 1 }, { 1, 2 } };
Console.WriteLine(findminSum(edges2, arr2, N2));
}
}