首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【LightOJ】1094 - Farthest Nodes in a Tree(树的直径)

【LightOJ】1094 - Farthest Nodes in a Tree(树的直径)

作者头像
FishWang
发布2025-08-26 15:09:10
发布2025-08-26 15:09:10
1940
举报

点击打开题目

1094 - Farthest Nodes in a Tree

PDF (English)

Statistics

Forum

Time Limit: 2 second(s)

Memory Limit: 32 MB

Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the tree whose distance is maximum amongst all nodes.

Input

Input starts with an integer T (≤ 10), denoting the number of test cases.

Each case starts with an integer n (2 ≤ n ≤ 30000) denoting the total number of nodes in the tree. The nodes are numbered from 0 to n-1. Each of the next n-1lines will contain three integers u v w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 10000) denoting that node u and v are connected by an edge whose weight is w. You can assume that the input will form a valid tree.

Output

For each case, print the case number and the maximum distance.

Sample Input

Output for Sample Input

2 4 0 1 20 1 2 30 2 3 50 5 0 2 20 2 1 10 0 3 29 0 4 50

Case 1: 100 Case 2: 80

Notes

Dataset is huge, use faster i/o methods.

树的直径的裸题,两次dfs即可。

代码如下:

代码语言:javascript
复制
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define MAX 40000
int n;
vector<int> mapp[MAX+5];
vector<int> dis[MAX+5];
int f[MAX+5];		//距离当前点的距离 
bool vis[MAX+5];
void init()
{
	for (int i = 0 ; i < n ; i++)
	{
		mapp[i].clear();
		dis[i].clear();
	}
}
int dfs(int x)
{
	int ans;		//最远点 
	int maxx = 0;		//最大距离 
	queue<int> q;		//存放根 
	CLR(vis,false);
	CLR(f,0);
	f[x] = 0;
	q.push(x);
	while (!q.empty())
	{
		int st = q.front();
		q.pop();
		vis[st] = true;
		for (int i = 0 ; i < mapp[st].size() ; i++)
		{
			if (!vis[mapp[st][i]])		//该点没有用过 
			{
				q.push(mapp[st][i]);
				f[mapp[st][i]] = f[st] + dis[st][i];
				if (f[mapp[st][i]] > maxx)
				{
					maxx = f[mapp[st][i]];
					ans = mapp[st][i];		//记录节点 
				}
			}
		}
	}
	return ans;
}
int main()
{
	int u;
	int Case = 1;
	scanf ("%d",&u);
	while (u--)
	{
		scanf ("%d",&n);
		init();
		for (int i = 1 ; i < n ; i++)
		{
			int t1,t2,t3;
			scanf ("%d %d %d",&t1,&t2,&t3);
			mapp[t1].push_back(t2);
			dis[t1].push_back(t3);
			mapp[t2].push_back(t1);		//求树的直径一定要双向存图 
			dis[t2].push_back(t3);
		}
		int st = dfs(0);		//任意从一点开始bfs
		int ans = dfs(st);
		printf ("Case %d: %d\n",Case++,f[ans]);
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Input
  • Output
  • Notes
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档