import java.util.*;
public class Main{
static Map<Integer, List<Integer>> edges;
static int dp[][];
static int w[];
public static void backstacking(int root){
int len = edges.get(root).size();
if (len == 0){
dp[root][0] = w[root];
dp[root][1] = 0;
System.out.println("-------------------------------");
return ;
}
for (int i=0; i<len; i++){
int cur = edges.get(root).get(i);
backstacking(cur);
dp[root][0] += dp[cur][1];
dp[root][1] += Math.max(dp[cur][0], dp[cur][1]);
}
dp[root][0] += w[root];
return ;
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
dp = new int[n][2];
edges = new HashMap<>();
w = new int[n];
for (int i=0; i<n; i++){
w[i] = in.nextInt();
edges.put(i, new ArrayList<Integer>());
}
int degree[] = new int[n];
for (int i=0; i<n-1; i++){
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
degree[x]++;
edges.get(y).add(x);
}
int root = 0;
for (int i=0; i<n; i++){
if (degree[i] == 0){
root = i;
break;
}
}
backstacking(root);
System.out.println(Math.max(dp[root][0], dp[root][1]));
return ;
}
}
该段代码执行案例2时,有时正确,有时会栈溢出,将
static Map<Integer,List<Integer>> edges;换成
static List<Integer> edges[];【注释部分】就不会栈溢出,,不太明白为啥??