不多说,直接上代码
下面展示一些 内联代码片
。
//求树的直径
//主要思路先随机找一个点(一般是1)找道离这个点最远的点(这个点一定在树的直径上),再在这个点的基础上再找一个离他最远的点,这个距离就是直径
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <ctype.h>
#include <deque>
using namespace std;
typedef long long ll;
typedef pair<ll,int> P;
//const ll mod=998244353;
const ll inf=0x3f3f3f3f3f3f3f3f;
//const int maxn=1e9+9;
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0)
#define mcy(a,b) memcpy(a,b,sizeof(a))
#define maxn 100000
struct node
{
int u,v,w,nex;
}edge[maxn*2+7];
int cnt=0;
int ans=0;
int flag=0;
int head[maxn+7];
int d[maxn+7];
void add(int x,int y,int z)
{
cnt++;
edge[cnt].u=x;
edge[cnt].v=y;
edge[cnt].w=z;
edge[cnt].nex=head[x];
head[x]=cnt;
}
void dfs(int x,int fa)//dfs找最远点
{
if(ans<d[x])
{
ans=d[x];
flag=x;
}
for(int i=head[x];i!=-1;i=edge[i].nex)//找到所有以x点为起点的边
{
int j=edge[i].v;
if(j==fa)continue;//剪掉这一条路径的上一个节点
d[j]=d[x]+edge[i].w;
dfs(j,x);
}
}
int main()
{
int n,m;
cin >> n;
mem(head,-1);
for(int i=1;i<=n-1;++i)
{
int x,y,z;
cin >> x >> y >> z;
add(x,y,z);
add(y,x,z);
}
dfs(1,0);
ans=0;//flag就是离一最远的点
d[flag]=0;//将flag点定位0,最远点距离就是直径
dfs(flag,0);
printf("%d\n",ans);
return 0;
}
下面展示一些 内联代码片
。
4
1 3 9
3 4 99
1 2 999
1107
Program ended with exit code: 0