题目描述
blablabla
样例
blablabla
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
Java 代码
import java.util.*;
import java.io.*;
public class Main{
static int[] happy;
static int[] h;
static int[] e;
static int[] ne;
static int idx = 0;
static int[][] f;
static int N;
static boolean[] st;
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter write = new PrintWriter(System.out);
public static void main(String[] args) throws IOException{
String[] s = read.readLine().split("\\s+");
N = Integer.parseInt(s[0]);
st = new boolean[N+1];
happy = new int[N+1];
h = new int[N+1];
e = new int[N+1];
ne = new int[N+1];
f = new int[N+1][2];
for (int i = 1; i <= N; i++) {
s = read.readLine().split("\\s+");
happy[i] = Integer.parseInt(s[0]);
}
Arrays.fill(h, -1);
for (int i = 1; i < N; i++) {
s = read.readLine().split("\\s+");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
add(b,a);
st[a] = true;
}
int root = 1;
while(st[root]){
root ++;
}
dfs(root);
write.print(Math.max(f[root][0], f[root][1]));
write.flush();
write.close();
read.close();
}
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][1] += f[j][0];
f[u][0] += Math.max(f[j][1], f[j][0]);
}
}
static void add(int a,int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
}