hdu 2196 Computer 树形dp 树中点最大距离
2015-11-09 15:00
337 查看
// hdu 2196 Computer 树形dp // // 题目大意: // // 求树上每个点到其他点的最大距离 // // 解题思路: // // 保存每个点到其子树的最大距离d[u][0]和次大距离d[u][1].对与 // 最大距离d[v][2]的求法和它的父亲u有关.如果v是在u的最大距离的子 // 树中,那么答案就是d[u][1] + dist[u,v]否则就是d[u][0] + dist[u,v] // 哎,自己的功力还是不够,这么经典的都是最近才知道,继续加油吧!!! #include <cstring> #include <algorithm> #include <iostream> #include <cstdio> #include <cmath> #include <string> #include <vector> #include <set> #include <queue> #include <map> #define For(x,a,b,c) for (int x = a; x <= b; x += c) #define Ffor(x,a,b,c) for (int x = a; x >= b; x -= c) #define cls(x,a) memset(x,a,sizeof(x)) using namespace std; typedef long long ll; const int MAX_N = 10008; const int INF = 0x3f3f3f3f; const ll MOD = 1e6; int N,M; struct node{ int v; int w; node(){ } node(int v,int w):v(v),w(w){ } }; vector<node> g[MAX_N]; int d[MAX_N][3]; void dfs1(int u,int fa){ int first = 0,second = 0; for (int i = 0;i < g[u].size();i ++){ int v = g[u][i].v; if (v == fa) continue; dfs1(v,u); int tmp = g[u][i].w + d[v][0]; if (first <= tmp){ second = first; first = tmp; } else if (second < tmp){ second = tmp; } } d[u][0] = first; d[u][1] = second; } void dfs2(int u,int fa){ for (int i = 0 ;i < g[u].size();i ++){ int v = g[u][i].v; if (v == fa) continue; int w = g[u][i].w; d[v][2] = max(d[v][2],max(d[u][2],d[v][0] + w == d[u][0] ? d[u][1] : d[u][0]) + w); dfs2(v,u); } } void input(){ for (int i = 1;i <= N ; i ++) g[i].clear(); for (int i = 2;i <= N;i ++){ int u,v; scanf("%d%d",&u,&v); g[i].push_back(node(u,v)); g[u].push_back(node(i,v)); } dfs1(1,-1); for (int i = 1;i <= N;i ++) d[i][2] = 0; dfs2(1,-1); for (int i = 1;i <= N;i ++){ printf("%d\n",max(d[i][0],d[i][2])); } } int main(){ //freopen("1.in","r",stdin); while(scanf("%d",&N)!=EOF){ input(); } return 0; }
相关文章推荐
- 树形DP 或 最小顶点覆盖=最大匹配(双向图)(HDU 1053)
- [BZOJ1017][JSOI2008][树形DP]魔兽地图DotR
- ZOJ3824 Fiber-optic Network
- hihocoder #1035 : 自驾旅行 III 树形DP
- POJ 3342
- URAL1018
- hdu1561 zoj3201
- poj 3107 Godfather
- zoj3201Tree of Tree
- Codeforces Round #135 (Div. 2)VD. Choosing Capital for Treeland
- POJ 1848 Tree
- HDU 1561 The more, The Better(树形DP)
- 树形dp简单总结
- Party at Hali-Bula
- zoj cut the tree(树形dp,小细节真的很多)
- poj 2486 Apple Tree(树形dp)
- poj 1155 TELE(树形泛化背包dp)
- 树形DP
- HDU 1520 Anniversary party (树形dp) 解题报告
- POJ 1463 Strategic game (树形DP) 解题报告