关注
第二题,每个结点 U 到子树中某结点 V 的最大边权和,有大佬帮我看看吗? import java.util.*;
public class Main {
static int [] dparray_weight; //每个结点 U 到子树中某结点 V 的最大边权和
static int [][] tree_edge; //记录边的权值
static int n; //结点个数
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = Integer.valueOf(sc.nextLine());
tree_edge = new int[n][n];
dparray_weight = new int[n];
init_tree_edge(); //初始化边矩阵,自己到自己为0,其余为int的最大值
//保存输入的边
for(int i=1;i<n;i++){
String[] temp = sc.nextLine().split(" ");
int u = Integer.valueOf(temp[0])-1;
int v= Integer.valueOf(temp[1])-1;
tree_edge[u][v] = Integer.valueOf(temp[2]);
}
dp_weight(0);
for(int i=0;i<n;i++)
System.out.print(dparray_weight[i]+" ");
}
public static int dp_weight(int index){
if( isleaf(index) ){
dparray_weight[index]=0;
return dparray_weight[index];
}
for(int j=0;j<n;j++)
if( j!=index && tree_edge[index][j] != Integer.MAX_VALUE ) //index到j有一条边
dparray_weight[index]=Math.max(dparray_weight[index], dp_weight(j)+ tree_edge[index][j]);
return dparray_weight[index];
}
public static boolean isleaf(int index){ //结点下标为index的结点是不是叶子结点
boolean flag =true;
for(int j=0;j<n;j++)
if( tree_edge[index][j] != Integer.MAX_VALUE && index!=j){
flag = false;
break;
}
return flag;
}
public static void init_tree_edge(){
for(int i=0;i<n;i++)
for (int j=0;j<n;j++)
if(i==j)
tree_edge[i][j]=0;
else
tree_edge[i][j]= Integer.MAX_VALUE;
}
public static void print_array(){
for(int i=0;i<n;i++){
for (int j=0;j<n;j++)
System.out.print(tree_edge[i][j]+" ");
System.out.println();
}
}
}
查看原帖
点赞 2
相关推荐

点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 面试问题记录 #
23026次浏览 377人参与
# 面试经验谈 #
14783次浏览 227人参与
# 京东TGT #
30475次浏览 152人参与
# 职场新人生存指南 #
334717次浏览 7177人参与
# 面试吐槽bot #
2913次浏览 36人参与
# 异地恋该为对方跳槽吗 #
24713次浏览 121人参与
# 硬件人更看重稳定还是高薪 #
39862次浏览 205人参与
# 对妈妈没说出口的话 #
7676次浏览 214人参与
# 硬件人秋招的第一个offer #
66188次浏览 1082人参与
# 机械求职避坑tips #
41632次浏览 355人参与
# 视觉/交互/设计招聘信息汇总 #
10040次浏览 595人参与
# 租房找室友 #
28540次浏览 147人参与
# 不考虑转正,实习多久合适 #
24786次浏览 119人参与
# 机械人,你的第一份感谢信是谁给的 #
22565次浏览 295人参与
# 新凯来求职进展汇总 #
34022次浏览 90人参与
# 假如我穿越到了妈妈的18岁 #
386次浏览 19人参与
# 上班苦还是上学苦呢? #
214079次浏览 1288人参与
# 滴滴工作体验 #
23906次浏览 123人参与
# 妈妈治愈了你哪些脆皮时刻 #
3131次浏览 81人参与
# 硬件人你反向读研了吗 #
40403次浏览 608人参与
# 学历or实习经历,哪个更重要 #
114827次浏览 753人参与