Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=2196
Give a tree the longest distance from each point in the tree to a point. Note that each point is required.
The diameter of the common tree is different, requiring each point, the number of points is 10000 so every point runs once DFS will time out. Therefore, a random Dfs point, find a point at this point as the origin point and then find the furthest point from it, and then find the tree diameter at the end of the point.
1#include <algorithm>2#include <iostream>3#include <iomanip>4#include <cstring>5#include <climits>6#include <complex>7#include <fstream>8#include <cassert>9#include <cstdio>Ten#include <bitset> One#include <vector> A#include <deque> -#include <queue> -#include <stack> the#include <ctime> -#include <Set> -#include <map> -#include <cmath> + - using namespacestd; + AtypedefstructEdge { at intV, W; - intNext; - }edge; - Const intMAXN =10010; - intN, ecnt; - intHEAD[MAXN]; inEdge e[maxn*MAXN]; - intDP[MAXN]; to intED, LP; + - voidinit () { theMemset (Head,-1,sizeof(head)); *ECNT =0; $ }Panax Notoginseng - voidAdde (intUintVintW) { theE[ECNT].V =v; +E[ECNT].W =W; AE[ecnt].next =Head[u]; theHead[u] = ecnt++; + } - $ voidDfsintUintPreintLen) { $ if(Len >LP) { -LP =Len; -ed =u; the } - for(inti = Head[u]; ~i; I=E[i].next) {Wuyi if(E[I].V = = pre)Continue; theDFS (E[I].V, u, Len +E[I].W); -DP[E[I].V] = max (DP[E[I].V], len+E[I].W); Wu } - } About $ intMain () { - //freopen ("in", "R", stdin); - intV, W; - while(~SCANF ("%d", &N)) { A init (); + for(inti =2; I <= N; i++) { thescanf"%d%d", &v, &W); - Adde (i, V, W); $ Adde (V, I, W); the } theLP =-1; theMemset (DP,0,sizeof(DP)); theDfs1, -1,0); -DFS (Ed,-1,0); inDFS (Ed,-1,0); the for(inti =1; I <= N; i++) { theprintf"%d\n", Dp[i]); About } the } the return 0; the}
[HDOJ2196] Computer (tree diameter tree-shaped DP)