跳到正文

个人记录

树的直径

zhouwc约 1 分钟
原文
文章信息与版本

文章信息

发布
2019年11月15日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
using namespace std;
int n,m,tot,p,ans;
int f[1000005],head[1000005],Next[1000005],v[1000005],w[10000005];
void add(int x,int y,int z)
{
	tot++;
	v[tot]=y;
	w[tot]=z;
	Next[tot]=head[x];
	head[x]=tot;
}
void dfs(int x,int fa)
{
	if (ans<f[x])
	{
		ans=f[x];
		p=x;
	}
	for (int i=head[x];i;i=Next[i])
	{
		int u=v[i];
		if (u==fa) continue;
		f[u]=f[x]+w[i];
		dfs(u,x);
	}
}
void find(int x)
{
	ans=0;
	f[x]=0;
	dfs(x,0);
}
int main()
{
	scanf("%d%d",&n,&m);
	for (int i=1;i<=m;i++)
	{
		int x,y,z;
		scanf("%d%d%d",&x,&y,&z);
		add(x,y,z);
		add(y,x,z);
	}
	find(1);
	find(p);
	printf("%d",ans);
}