[题目链接]
https://www.lydsy.com/JudgeOnline/problem.php?id=3363
[算法]
树的直径
[代码]
#include<bits/stdc++.h> using namespace std; #define MAXN 100010 struct edge { int to,w,nxt; } e[MAXN << 1]; int i,n,m,u,v,w,ans,tot; char t[10]; int head[MAXN],d[MAXN]; inline void addedge(int u,int v,int w) { tot++; e[tot] = (edge){v,w,head[u]}; head[u] = tot; } inline void dfs(int u,int fa) { int i,v,w; for (i = head[u]; i; i = e[i].nxt) { v = e[i].to; w = e[i].w; if (v == fa) continue; dfs(v,u); ans = max(ans,d[u] + d[v] + w); d[u] = max(d[u],d[v] + w); } } int main() { scanf("%d%d",&n,&m); for (i = 1; i <= m; i++) { scanf("%d%d%d%s",&u,&v,&w,&t); addedge(u,v,w); addedge(v,u,w); } dfs(1,0); printf("%d ",ans); return 0; }