没有上司的舞会
状态转移方程:
f
(
u
,
0
)
+
=
∑
m
a
x
(
f
(
s
i
,
0
)
,
f
(
s
i
,
1
)
)
f
(
u
,
1
)
+
=
∑
f
(
s
i
,
0
)
\begin{aligned} &f(u,0)+=\sum max(f(s_i,0),f(s_i,1)) \\ &f(u,1)+=\sum f(s_i,0) \end{aligned}
f(u,0)+=∑max(f(si,0),f(si,1))f(u,1)+=∑f(si,0)
import java.io.*;
import java.util.*;
public class Main{
static int N=6010;
static int[] happy=new int[N];
static int[] h=new int[N];
static int[] e=new int[N];
static int[] ne=new int[N];
static int idx=0;
static int[][] f=new int[N][2];
static boolean[] has_father=new boolean[N];
public static void main(String[] args)throws IOException{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(in.readLine());
for(int i=1;i<=n;i++)
happy[i]=Integer.parseInt(in.readLine());
String[] strs;
Arrays.fill(h,-1);
for(int i=0;i<n-1;i++){
strs=in.readLine().split(" ");
int a=Integer.parseInt(strs[0]);
int b=Integer.parseInt(strs[1]);
has_father[a]=true;
add(b,a);
}
int root=1;
while(has_father[root])root++;
dfs(root);
System.out.println(Math.max(f[root][0],f[root][1]));
}
static void add(int a,int b){
e[idx]=b;ne[idx]=h[a];h[a]=idx++;
}
static void dfs(int u){
f[u][1]+=happy[u];
for(int i=h[u];i!=-1;i=ne[i]){
int j=e[i];
dfs(j);
f[u][0]+=Math.max(f[j][0],f[j][1]);
f[u][1]+=f[j][0];
}
}
}