题目
实验室里原先有一台电脑(编号为1),最近氪金带师咕咕东又为实验室购置了N-1台电脑,编号为2到N。每台电脑都用网线连接到一台先前安装的电脑上。但是咕咕东担心网速太慢,他希望知道第i台电脑到其他电脑的最大网线长度,但是可怜的咕咕东在不久前刚刚遭受了宇宙射线的降智打击,请你帮帮他。
提示: 样例输入对应这个图,从这个图中你可以看出,距离1号电脑最远的电脑是4号电脑,他们之间的距离是3。 4号电脑与5号电脑都是距离2号电脑最远的点,故其答案是2。5号电脑距离3号电脑最远,故对于3号电脑来说它的答案是3。同样的我们可以计算出4号电脑和5号电脑的答案是4.
Input
输入文件包含多组测试数据。对于每组测试数据,第一行一个整数N (N<=10000),接下来有N-1行,每一行两个数,对于第i行的两个数,它们表示与i号电脑连接的电脑编号以及它们之间网线的长度。网线的总长度不会超过10^9,每个数之间用一个空格隔开。
Output
对于每组测试数据输出N行,第i行表示i号电脑的答案 (1<=i<=N).
Sample Input
5
1 1
2 1
3 1
1 1
Sample Output
3
2
3
4
4
解题思路
题意是给出若干条无向线,要求我们输出图中每个点到达其他点的最大值。某个点能到达的最大路径的点一定是只有一条线相连的点,因此为了简化搜索过程,我们从只连接一条网线的电脑开始进行 dfs 搜索,统计某个点到达图中其他点的最大值。
与某台电脑相连的网线可以用邻接链表来存储,一条网线分别用两个表示单向连接的结点 node 来表示。a、b 表示方向为 a-->b ,l 为网线长度,m 为这个方向上的 dfs 搜索结果。完成数据的输入后,选取出点为 1 的结点,从这些结点开始进行 dfs 搜索,最后即可从 result 数组中读取并输出结果。
程序源码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
struct node { //网线结点,表示 a --> b,长度为 l
int a;
int b;
int l;
int m; //标记位,如果已经搜索过,则标记 1
node* next;
node(int aa, int bb, int ll, node* nnext) :a(aa), b(bb), l(ll), next(nnext) { //初始化列表
m = -1;
}
node(node* nnext) :next(nnext) {}
};
node** L; //某台电脑连出的网线
int* touch; //dfs标记
int* result; //存结果
int* point; //统计结点相连的点
int dfs(node* currentnode, const int& flag) { //dfs搜索函数 参数:当前节点 标记位
int themax = 0, current;
node* thisnode = currentnode;
while (thisnode != NULL) { //依次遍历当前节点连出的网线结点
if (touch[thisnode->b] != flag) { //这个点本次dfs未到达过
touch[thisnode->b] = flag; //打上到达标记
if (thisnode->m == -1) { // a --> b 方向之前没有遍历过
current = dfs(L[thisnode->b], flag) + thisnode->l; //以b点dfs搜索获得其到最远端点的距离
thisnode->m = current; //保存dfs获得的结果
}
else { // a --> b 方向之前遍历过了,直接拿结果 thisnode->m;
current = thisnode->m;
}
if (current > themax) { //取较大者
themax = current;
}
}
thisnode = thisnode->next; //移动到下一条线
}
if (result[currentnode->a] < themax) { //保存较大者
result[currentnode->a] = themax;
}
return themax; //返回结果
}
int main() {
int n, a, b;
while (scanf("%d", &n) != EOF) { //获取多组数据
L = new node * [10001]{ NULL };
touch = new int[10001]{ 0 };
result = new int[10001]{ 0 };
point = new int[10001]{ 0 };
for (int i = 2; i <= n; i++) {
scanf("%d%d", &a, &b); //获取并添加网线,双向
L[i] = new node(i, a, b, L[i]); // i --> a
L[a] = new node(a, i, b, L[a]); // a --> i
touch[i]++; //统计结点相连的点
touch[a]++;
}
if (n < 2) { //特殊情况,直接返回结果
cout << 0 << endl;
continue;
}
int totalPoint = 0; //出点计数为1的点的总数
for (int i = 1; i <= n; i++) { //找到并保存出点为1的点
if (touch[i] == 1) {
point[totalPoint] = i;
totalPoint++;
}
}
for (int i = 0; i < totalPoint; i++) { //为每个出点为1的点进行dfs
touch[point[i]] = i - totalPoint - 5; //每次dfs都打上不同的标记
dfs(L[point[i]], i - totalPoint - 5); //dfs
}
for (int i = 1; i <= n; i++) { //输出结果
printf("%d\n", result[i]);
}
delete[] L; //释放空间
delete[] touch;
delete[] result;
delete[] point;
}
return 0;
}