题目描述
思路分析
dfs+无根树变有根树
代码实现
package lanqiao;import java.util.Scanner;public class Main {//提升作用域public static int n;public static int[] w;//每个点的权重public static int[] ww;//每个点作为根节点时能得到的最大权和public static int[][] g;//存储图对应的邻接矩阵public static int ans;/*** 以root为根,算出最大的权和* @param root* @param father* 无根树转有根树*/public static void dfs(int root,int father){ww[root]=w[root];for (int i = 0; i < g[root].length; i++) {int son=g[root][i];//其中一个孩子if(son!=father){dfs(son,root);if(ww[son]>0){ww[root]+=ww[son];}}}if(ww[root]>ans)ans=ww[root];}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n=scanner.nextInt();w=new int[n+1];ww=new int[n+1];g=new int[n+1][n+1];for (int i = 1; i <= n; i++) {w[i]=scanner.nextInt();}for (int j = 0; j < n - 1; j++) {//n-1条边int u,v;u=scanner.nextInt();v=scanner.nextInt();g[u][v]=v;g[v][u]=u;}dfs(1,0);System.out.println(ans);}
}