Farthest Nodes in a Tree

本文详细解析了如何在加权无向图中寻找树的直径,即两节点间最大距离。通过两次深度优先搜索,首先从任意节点找到最远节点,再从此节点出发找到最远节点,这两节点间距离即为树的直径。

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

Farthest Nodes in a Tree

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
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-1 lines 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

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

Sample Output

    Case 1: 100
    Case 2: 80

这个题刚开始一直不理解,可能是对树的的直径比较陌生吧,可后来看看了看学长给我板子。我去咋这么简单emmm,我真是个智障呀。只要从任意一个节点出发然后找到距离他最远的节点,然后再让这个最远的出发去找距离这个最远的,这两个节点的距离就是树的直径!
这就是一个简单的板子题

#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
typedef pair<int,int> pa;

bool flag[100100];
int step[100100];
vector<pa>v[100100];
int a,b,c,sum;
int t,n;

int dfs(int x)
{
    sum=0;
	memset(flag,0,sizeof flag);
	memset(step,0,sizeof step);
	queue<int>q;
	q.push(x);
	flag[x]=1;
	int yy=0;
	while(!q.empty() )
	{
		int xx=q.front() ;
		q.pop() ;
		if(step[xx]>sum)
		{
			sum=step[xx];
			yy=xx;
		}
		pa p;
		for(int i=0;i<v[xx].size() ;i++)
		{
			p=v[xx][i];
			int y=p.first ;
			if(!flag[y])
			{
				flag[y]=1;
				step[y]=step[xx]+p.second;
				q.push(y);
			}
		}
	}
	return yy;
}
int main()
{
	ios::sync_with_stdio(false);
	cin>>t;
	
		for(int i=1;i<=t;i++)
		{
			cin>>n;
			for(int k=0;k<n;k++) 
			    v[k].clear() ;
			for(int j=1;j<n;j++)
			{
				cin>>a>>b>>c;
				v[a].push_back(make_pair(b,c));//双向存储便于查找
			 	v[b].push_back(make_pair(a,c));	 
			}
			dfs(dfs(0));
			cout<<"Case "<<i<<": "<<sum<<endl;
		}
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值