AcWing 285. 没有上司的舞会Java
原题链接
简单
作者:
henhen敲
,
2020-04-26 13:54:02
,
所有人可见
,
阅读 682
import java.io.*;
class Main{
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static int nextInt() throws Exception{
in.nextToken();
return (int)in.nval;
}
static int[] h, e, ne, v;
static int idx = 0;
static int[][] f;
static void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
static void DFS(int root){
//if(f[root][1]&&f[root][0]>0) return;
int sum0, sum1;
sum0 = 0; sum1 = 0;
for(int i=h[root]; i!=-1; i=ne[i]){
int r = e[i];
DFS(r);
sum0 += f[r][1];
sum1 += f[r][0];
}
f[root][1] = -0x3f3f3f3f;
f[root][0] = -0x3f3f3f3f;
f[root][1] = sum1+v[root];
f[root][0] = Math.max(sum1, sum0);
}
public static void main(String[] args)throws Exception{
int n = nextInt();
h = new int[n+1];
e = new int[n];
ne = new int[n];
f = new int[n+1][2];
v = new int[n+1];
for(int i=1; i<=n; i++){
v[i] = nextInt();
h[i] = -1;
}
boolean[] roots = new boolean[n+1];
for(int i=0; i<n-1; i++){
int a, b;
b = nextInt(); a = nextInt();
add(a, b);
roots[b] = true;
}
int root=0;
for(int i=1; i<=n; i++) if(!roots[i]) root = i;
//out.print(root);
DFS(root);
out.print(Math.max(f[root][0],f[root][1]));
out.close();
}
}
同为java我不点赞谁点赞
都不点赞