紫书动规 P282的问题 hdu2196 树形dp
来源:互联网 发布:mysql删除表中数据 编辑:程序博客网 时间:2024/05/29 09:43
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2196
题意:
题解:
http://blog.csdn.net/shuangde800/article/details/9732825
f[i][0],表示顶点为i的子树的,距顶点i的最长距离
f[i][1],表示Tree(i的父节点)-Tree(i)的最长距离+i跟i的父节点距离
要求所有的f[i][0]很简单,只要先做一次dfs求每个结点到叶子结点的最长距离即可。
然后要求f[i][1], 可以从父节点递推到子节点,
代码:
#include <bits/stdc++.h>using namespace std;typedef long long ll;#define MS(a) memset(a,0,sizeof(a))#define MP make_pair#define PB push_backconst int INF = 0x3f3f3f3f;const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;inline ll read(){ ll x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f;}//////////////////////////////////////////////////////////////////////////const int maxn = 1e5+10;struct node{ int v,w;};vector<node> g[maxn];int vis[maxn],f[maxn][2];int dfs1(int u){ vis[u] = 1; f[u][0] = 0; for(int i=0; i<(int)g[u].size(); i++){ int v = g[u][i].v, w = g[u][i].w; if(vis[v]) continue; f[u][0] = max(f[u][0],dfs1(v)+w); } return f[u][0];}void dfs2(int u){ vis[u] = 1; int max1=0,max2=0,v1,v2; for(int i=0; i<(int)g[u].size(); i++){ int v = g[u][i].v, w = g[u][i].w; if(vis[v]) continue; // 不能返回到父节点 int tmp = f[v][0]+w; if(tmp > max1){ max2 = max1; v2 = v1; max1 = tmp; v1 = v; }else if(tmp > max2){ max2 = tmp; v2 = v; } } if(u != 1){ int tmp = f[u][1]; int v = -1; if(tmp > max1){ max2 = max1; v2 = v1; max1 = tmp; v1 = v; }else if(tmp > max2){ max2 = tmp; v2 = v; } } for(int i=0; i<(int)g[u].size(); i++){ int v = g[u][i].v, w = g[u][i].w; if(vis[v]) continue; if(v == v1) f[v][1] = max2 + w; else f[v][1] = max1 + w; // cout << v << " " << f[v][1] << endl; dfs2(v); }}int main(){ int n; while(scanf("%d",&n) == 1){ for(int i=0; i<=n; i++) g[i].clear(); for(int i=2; i<=n; i++){ int v,w; cin >> v >> w; g[i].push_back(node{v,w}); g[v].push_back(node{i,w}); } MS(f); MS(vis); dfs1(1); MS(vis); dfs2(1); for(int i=1; i<=n; i++) cout << max(f[i][0],f[i][1]) << endl; } return 0;}
0 0
- 紫书动规 P282的问题 hdu2196 树形dp
- hdu2196 树的直径或者树形dp
- hdu2196-树形dp|树的直径-Computer
- 【树形DP】 hdu2196 Computer
- HDU2196 经典树形DP
- hdu2196树形dp
- HDU2196:Computer(树形DP)
- hdu2196 Computers 树形DP
- hdu2196 树形DP
- HDU2196 - Computer (树形DP)
- hdu2196(树形dp)
- hdu2196 树形dp
- hdu2196经典树形dp
- HDU2196 Computer(树形DP)
- hdu2196 Computer 【树形dp】
- 【HDU2196】【树形DP】
- hdu2196 Computer【树形DP】
- 树形DP-HDU2196
- PHP基础知识数组
- Volley 集成 okhttp3 的步骤
- java并发编程--共享对象的可见性
- jsp中的4大域对象
- RMQ求LCA
- 紫书动规 P282的问题 hdu2196 树形dp
- 博为峰Java技术文章 ——JavaSE Swing 下拉列表框的事件处理
- 贪心算法在找钱问题上的使用
- PHP基础知识运算符
- ehcache和spring
- CCF201509-1-数列分段
- LeetCode [292. Nim Game] 难度[easy]
- 设计模式学习--职责链模式
- ORA-00845: MEMORY_TARGET not supported on this system