Link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 2196
Every computer connects to another computer with a certain length. Finally, all the computers are connected to a tree, ask the maximum distance between each computer and other computers.
Idea: this is a classic topic of tree-like DP. It takes two DFS sessions, for the first time, DFS finds the distance between all the nodes on the tree and the distance between them in different sub-trees (Dynamic Planning in recursion). The second time DFS updates the final answer from the root, for the node u updated each time, the longest distance may be the child tree from u, or the longest distance from the Father's Day node of U, if u's Father's Day is updated from u during the first DFS process, the longest distance of U cannot be updated from u's father's day node, however, it is possible to update the distance from the Father's Day point of U, which is the reason for recording the distance of the node each time it is updated.
Code:
#include <algorithm>#include <cmath>#include <cstdio>#include <cstdlib>#include <cstring>#include <ctime>#include <ctype.h>#include <iostream>#include <map>#include <queue>#include <set>#include <stack>#include <string>#include <vector>#define eps 1e-8#define INF 0x7fffffff#define maxn 10005#define PI acos(-1.0)#define seed 31//131,1313typedef long long LL;typedef unsigned long long ULL;using namespace std;int dp[maxn][2],from[maxn],head[maxn],top;void init(){ memset(head,-1,sizeof(head)); memset(dp,0,sizeof(dp)); memset(dp,0,sizeof(dp)); top=0;}struct Edge{ int v,w; int next;} edge[maxn*2];void add_edge(int u,int v,int w){ edge[top].v=v; edge[top].w=w; edge[top].next=head[u]; head[u]=top++;}void dfs_first(int u,int f){ from[u]=u; for(int i=head[u]; i!=-1; i=edge[i].next) { int v=edge[i].v,w=edge[i].w; if(v==f) continue; dfs_first(v,u); if(dp[v][0]+w>dp[u][0]) { from[u]=v; dp[u][1]=dp[u][0]; dp[u][0]=dp[v][0]+w; } else if(dp[v][0]+w>dp[u][1]) dp[u][1]=dp[v][0]+w; }}void dfs_second(int u,int f,int k){ if(u!=f) if(from[f]!=u) { if(dp[f][0]+k>dp[u][0]) { from[u]=f; dp[u][1]=dp[u][0]; dp[u][0]=dp[f][0]+k; } else if(dp[f][0]+k>dp[u][1]) dp[u][1]=dp[f][0]+k; } else { if(dp[f][1]+k>dp[u][0]) { from[u]=f; dp[u][1]=dp[u][0]; dp[u][0]=dp[f][1]+k; } else if(dp[f][1]+k>dp[u][1]) dp[u][1]=dp[f][1]+k; } for(int i=head[u]; i!=-1; i=edge[i].next) { int v=edge[i].v,w=edge[i].w; if(v==f) continue; dfs_second(v,u,w); }}int main(){ int T,v,w; while(~scanf("%d",&T)) { init(); for(int i=2; i<=T; i++) { scanf("%d%d",&v,&w); add_edge(v,i,w); add_edge(i,v,w); } dfs_first(1,1); dfs_second(1,1,0); for(int i=1;i<=T;i++) printf("%d\n",dp[i][0]); } return 0;}
HDU 2196 computer tree DP classic questions