Test instructions
Give the computer network connection tree, ask each node for the longest distance from the starting point
Analysis:
The problem began to think, put a period of time, and later noticed that the problem on the example, the longest distance of each node can be determined by the maximum length of the parent node, the second long distance, and the longest distance of the child nodes (whichever is the largest). First, use a Dfs to find the maximum distance that each node is determined by each subtree, and then use a DFS to push the maximum distance from the parent node to each child node.
#include <map> #include <set> #include <list> #include <cmath> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <string> #include <cctype> #include <complex> #include <cassert> #include <utility> #include <cstring> #include <cstdlib># Include <iostream> #include <algorithm>using namespace std;typedef pair<int,int> pii;typedef long Long ll; #define Lson l,m,rt<<1#define Pi ACOs ( -1.0) #define Rson m+1,r,rt<<11#define all 1,n,1#define read fre Open ("In.txt", "R", stdin) #define N 10010const ll infll = 0x3f3f3f3f3f3f3f3fll;const int inf= 0x7ffffff;const int mod = 1000000007;struct edge{int t,d;};/ /p[i] The longest distance from the parent node//dp[i] The longest distance from the child tree//g[i] The subordinate to the sub-tree distance int Dp[n],p[n],g[n],n,longest[n];vector<edge>e[n];int DFS ( int root) {if (E[root].size () ==0) return 0; if (Dp[root]) return dp[root];//memory search int tmp; For (int. i=0;i<e[root].size (); ++i) {inT son=e[root][i].t; int cost=e[root][i].d; if (Dfs (son) +cost>dp[root]) {g[root]=dp[root]; Dp[root]=dp[son]+cost; Tmp=son; } else if (Dp[son]+cost>g[root]) g[root]=dp[son]+cost; longest[root]=tmp;//the longest distance of the sub-node to save, convenient back from the next long distance update the longest return dp[root];} void dfs1 (int root) {for (int i=0;i<e[root].size (); ++i) {int son=e[root][i].t; int cost=e[root][i].d; if (Son==longest[root])//If the child node gets the longest distance, the parent node from the parent node's maximum distance and from the sub-tree to update P[son]=max (P[root],g[root]) +cost; else P[son]=max (P[root],dp[root]) +cost;//Otherwise, the maximum distance from the parent node from the parent node and the longest remote update from the subtree dfs1 (son); }}int Main () {while (~SCANF ("%d", &n)) {Edge B; int A; Memset (Dp,0,sizeof (DP)); memset (P,0,sizeof (p)); memset (G,0,sizeof (g)); for (int i=1;i<=n;++i) {e[i].clear (); } for (int i=2;i<=n;++i) {scanf ("%d%d", &A,&B.D); b.t=i; E[a].push_back (b); } dfs (1); DFS1 (1); for (int i=1;i<=n;++i) {printf ("%d\n", Max (P[i],dp[i])); }}return 0;}
HDU 2196-computer (tree-shaped DP)