Two Dfs, first search from the bottom up, record each point to the sub-tree of the longest distance and the second long distance. The goal of the second long distance is if, at the time of the second update, the longest distance is in the same direction as that of the child, it cannot be used for the longest distance and can only be updated with a second long distance. So the second time DFS is to update the status from the top down.
The code is as follows:
#include <iostream> #include <string.h> #include <math.h> #include <queue> #include < algorithm> #include <stdlib.h> #include <map> #include <set> #include <stdio.h>using namespace std; #define LL __int64#define Pi ACOs ( -1.0) const int Mod=100000000;const int Inf=0x3f3f3f3f;const double eqs=1e -8;int head[11000], CNT, dp[11000][3], id[11000][3];struct node {int u, V, W, next;} edge[30000];void Add (int u, I NT V, int w) {edge[cnt].v=v; Edge[cnt].w=w; Edge[cnt].next=head[u]; head[u]=cnt++;} void dfs1 (int u, int fa) {int i; for (i=head[u]; i+1; i=edge[i].next) {int v=edge[i].v; if (V==FA) continue; DFS1 (V,u); if (DP[U][1]<DP[V][0]+EDGE[I].W) {DP[U][1]=DP[V][0]+EDGE[I].W; Id[u][1]=v; if (Dp[u][1]>dp[u][0]) {swap (dp[u][0],dp[u][1]); Swap (id[u][1],id[u][0]); }}}}void DFS2 (int u, int fa) {int i, TMP; for (i=head[u]; i+1; i=edge[i].next) {int v=edge[i].v; if (V==FA) continue; if (id[u][0]==v) tmp=dp[u][1]; else tmp=dp[u][0]; if (dp[v][1]<edge[i].w+tmp) {dp[v][1]=edge[i].w+tmp; Id[v][1]=u; if (Dp[v][1]>dp[v][0]) {swap (dp[v][1],dp[v][0]); Swap (id[v][1],id[v][0]); }} DFS2 (V,u); }}void init () {memset (head,-1,sizeof (head)); cnt=0;} int main () {int n, I, U, V, W; while (scanf ("%d", &n)!=eof) {init (); for (i=2; i<=n; i++) {scanf ("%d%d", &v,&w); Add (I,V,W); Add (V,I,W); } memset (Dp,0,sizeof (DP)); DFS1 (1,0); DFS2 (1,0); for (I=1; i<=n; i++) {printf ("%d\n", dp[i][0]); }} return 0;}
HDU 2196 computer (tree-shaped DP)