大臣的旅费

本文介绍了一个名为“大臣的旅费”的算法问题及其解决方案。该算法通过深度优先搜索找到图中最远的距离,并据此计算出特定的旅费公式。文章详细展示了如何构建图的数据结构并进行递归遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package 搜索;




import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.ArrayList;


public class 大臣的旅费{
private static BufferedInputStream in = new BufferedInputStream(System.in);
private static ArrayList<Node> n = new ArrayList<Node>();
private static Integer dis = 0;
private static Integer pow = 0;


public static void main(String[] args) throws IOException {
int size = readInt();


for (int i = 0; i < size; i++) {
n.add(null);
}


for (int i = 1; i < size; i++) {
int x = readInt() - 1;
int y = readInt() - 1;
int d = readInt();


Node node = new Node();
node.nextSide = n.get(x);
node.con = y;
node.power = d;
n.set(x, node);


node = new Node();
node.nextSide = n.get(y);
node.con = x;
node.power = d;
n.set(y, node);
}
away(0, 0, -1);
pow = 0;
away(dis, 0, -1);
System.out.println(pow * 10 + (1 + pow) * pow / 2);
}


private static void away(int index, int power, int from) {
if (pow < power) {
pow = power;
dis = index;
}


Node node = n.get(index);


while (node != null) {
if (node.con == from) {
node = node.nextSide;
continue;
}


away(node.con, power + node.power, index);


node = node.nextSide;
}
}


private static int readInt() throws IOException {
int i, sum = 0;


while (((i = in.read()) & 48) != 48 || i > 57)
;


for (; (i & 56) == 48 || (i & 62) == 56; i = in.read())
sum = sum * 10 + (i & 15);


return sum;
}


private static class Node {
int power;
int con;
Node nextSide;


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值