Problem Solving Ideas:
To find the two endpoints of the tree's diameter, the farthest distance from each node to the other points on the tree must be the longest distance between the two endpoints.
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath > #include <vector> #include <queue> #define LL long longusing namespace Std;const int maxn = 100000 + 10;stru CT edge{int to, Next, W;} edge[2 * maxn];int tot;int head[maxn];int dis[maxn];int N, M;int d[maxn];void init () {tot = 0; Memset (Head,-1, sizeof (head)); memset (d, 0, sizeof (d)); void Addedge (int u, int v, int w) {edge[tot].to = v; Edge[tot].next = Head[u]; EDGE[TOT].W = W; Head[u] = tot++;} int dfs (int u, int pre =-1) {int ans = u; for (int i=head[u];i!=-1;i=edge[i].next) {int v = edge[i].to; if (v = = pre) continue; DIS[V] = Dis[u] + edge[i].w; int dv = DFS (V, u); if (Dis[ans] < DIS[DV]) ans = dv; } return ans; int solve (int u) {dis[u] = 0; u = DFS (u); Dis[u] = 0; int v = DFS (u); for (int i=1;i<=n;i++) d[i] = max (D[i], dis[i]); DIS[V] = 0; DFS (v); for (int i=1;i<=n;i++) D[i] = max (D[i], dis[i]); for (int i=1;i<=n;i++) cout << d[i] << Endl;} int main () {while (scanf ("%d", &n)!=eof) {int V, W; Init (); for (int i=2;i<=n;i++) {scanf ("%d%d", &v, &w); Addedge (i, V, W); Addedge (V, I, W); } solve (1); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 2196 computer (maximum distance from each node to other points on the tree)