关于猿辅导笔试
第二题我一直显示数组越界,只过了75% 有没有大佬AC的贴下代码,或者帮我看看😂
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Node[] nodes = new Node[n];
for(int i=0;i<n;i++){
nodes[i] = new Node();
}
int root = -1;
max = Long.MIN_VALUE;
for(int i=0;i<n;i++){
int v = sc.nextInt();
int p = sc.nextInt();//
nodes[i].val = v;
if(p==0){
root = i;
}else {
nodes[p-2].childs.add(nodes[i]);
}
}
dfs(nodes[root]);
System.out.println(max%1000000003);
}
static long max;
public static long dfs(Node root){
long val = root.val;
for(Node child:root.childs){
long add = dfs(child);
if(add>0)val+=add;
}
max = Math.max(max,val);
return val;
}
static class Node{
long val;
List<Node> childs = new ArrayList<>();
}
} 