标签:
有意思的题目,但是题目描述不正确(貌似阿三哥出的题目),让我走了一些弯路,很tmd无语。。输入严格来说根本不是树,是图来的,因为边是无向边。。但是它的输入保证了是没有环路的图,所以某种程度上可以看做是树(任何一个节点都可以为根节点,然后递归地把每个节点的邻居看做子节点)。
不过话说回来如果一开始告诉我这个图,我还真想不出来解法。。但是因为它“误导”了我,让我认为它是一颗树后,问题就简单了,每个树节点递归地存储它子树的总和。然后深度遍历即可。。
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int n;
static int[] nodevals;
static LinkedList<Integer>[] nodes;
static int[] nodesum;
static int root;
static int minDif = Integer.MAX_VALUE;
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
nodevals = new int[n+1];
nodes = new LinkedList[n+1];
nodesum = new int[n+1];
for(int i = 1;i<=n;i++)
{
nodevals[i] = scan.nextInt();
nodes[i] = new LinkedList<Integer>();
}
for(int i = 1; i<n;i++)
{
int par = scan.nextInt();
int chd = scan.nextInt();
nodes[par].addFirst(chd);
nodes[chd].addFirst(par);
}
depthSum(1,-1);
depthMinDif(1,-1);
System.out.println(minDif);
}
static int depthSum(int nodeInd,int par)
{
nodesum[nodeInd] += nodevals[nodeInd];
for(int chd : nodes[nodeInd]){
if(chd == par)
continue;
nodesum[nodeInd]+=depthSum(chd,nodeInd);
}
return nodesum[nodeInd] ;
}
static void depthMinDif(int nodeInd, int par){
int tmpdif = Math.abs(nodesum[1] - 2 * nodesum[nodeInd]);
if(tmpdif < minDif)
minDif = tmpdif;
for(int chd : nodes[nodeInd]){
if(chd == par)
continue;
depthMinDif(chd,nodeInd);
}
}
}标签:
原文地址:http://blog.csdn.net/tspatial_thunder/article/details/42834981