树的直径

zhouwc

2019-11-15 23:29:01

Personal

```cpp #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); } ```