using
System;
using
System.Collections.Generic;
public
class
GFG
{
static
void
Dfs(
int
u,
int
p, List<
int
>[] adj,
long
[,] ans, List<
int
> a,
bool
[] lef)
{
bool
isLeaf =
true
;
foreach
(
int
v
in
adj[u])
{
if
(p != v)
{
isLeaf =
false
;
ans[v, 0] = Math.Max(ans[v, 0], ans[u, 1] + a[v]);
ans[v, 1] = Math.Max(ans[v, 1], ans[u, 0] - a[v]);
Dfs(v, u, adj, ans, a, lef);
}
}
lef[u] = isLeaf;
}
static
long
BestNode(
int
n, List<
int
> A, List<
int
> P)
{
long
[,] v =
new
long
[n, 2];
for
(
int
i = 0; i < n; i++)
{
v[i, 0] = A[i];
}
for
(
int
i = 0; i < P.Count; i++)
{
if
(P[i] != -1)
{
P[i] -= 1;
}
}
List<
int
>[] adj =
new
List<
int
>[n];
for
(
int
i = 0; i < n; i++)
{
adj[i] =
new
List<
int
>();
}
for
(
int
i = 1; i < n; i++)
{
adj[i].Add(P[i]);
adj[P[i]].Add(i);
}
bool
[] lef =
new
bool
[n];
Dfs(0, -1, adj, v, A, lef);
long
ans =
long
.MinValue;
for
(
int
i = 0; i < n; i++)
{
if
(lef[i])
ans = Math.Max(ans, Math.Max(v[i, 0], v[i, 1]));
}
return
ans;
}
public
static
void
Main(
string
[] args)
{
int
N = 3;
List<
int
> A =
new
List<
int
> { 1, 2, 3 };
List<
int
> P =
new
List<
int
> { -1, 1, 1 };
long
bestNodeValue = BestNode(N, A, P);
Console.WriteLine(
"The best node value: "
+ bestNodeValue);
}
}