HDU 3848 CC On The Tree(树形dp)
2017-09-20 15:38
459 查看
http://acm.hdu.edu.cn/showproblem.php?pid=3848
题意:
求一棵树上两个叶子结点之间的最短距离。
思路:
两个叶子节点之间一定会经过非叶子节点,除非只有两个节点。
所以我们只需要维护离每个非叶子节点最远的叶子节点距离和次远距离,两者相加即是两个叶子节点之间的距离。
题意:
求一棵树上两个叶子结点之间的最短距离。
思路:
两个叶子节点之间一定会经过非叶子节点,除非只有两个节点。
所以我们只需要维护离每个非叶子节点最远的叶子节点距离和次远距离,两者相加即是两个叶子节点之间的距离。
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<sstream> #include<vector> #include<stack> #include<queue> #include<cmath> #include<map> #include<set> using namespace std; typedef long long ll; typedef pair<int,int> pll; const int INF = 0x3f3f3f3f; const int maxn = 10000+5; int n; int d[maxn][2]; vector<pll> G[maxn]; void dfs(int u, int fa) { d[u][0]=d[u][1]=INF; if(G[u].size()==1) { d[u][0]=0; return ; } for(int i=0;i<G[u].size();i++) { int v=G[u][i].first; int w=G[u][i].second; if(v==fa) continue; dfs(v,u); if(d[u][0]>d[v][0]+w) { d[u][1]=d[u][0]; d[u][0]=d[v][0]+w; } else if(d[u][1]>d[v][0]+w) d[u][1]=d[v][0]+w; } } int main() { //freopen("in.txt","r",stdin); while(~scanf("%d",&n) && n) { for(int i=1;i<=n;i++) G[i].clear(); for(int i=1;i<n;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); G[u].push_back(make_pair(v,w)); G[v].push_back(make_pair(u,w)); } if(n==2) { printf("%d\n",G[1][0].second); continue; } int i; for(i=1;i<=n;i++) if(G[i].size()>1) break; dfs(i,-1); int ans=INF; for(int i=1;i<=n;i++) ans=min(ans,d[i][0]+d[i][1]); printf("%d\n",ans); } return 0; }
相关文章推荐
- hdu 3848 CC on the tree 简单树形dp
- HDU 3848 CC On The Tree 树形DP
- HDU - 3848 CC On The Tree [多端BFS]
- hdu 3848 CC On The Tree
- HDU 3848 CC On The Tree
- hdu 3848 CC On The Tree
- HDU 3848 CC On The Tree
- hdu 3848 CC On The Tree
- [HDU 3848]CC On The Tree[dfs]
- HDU3848 CC On The Tree, 树形DP
- 【HDU 3848 CC On The Tree】+ 递归
- hdu 4916 Count on the path(树形dp)
- HDOJ 题目3848 CC On The Tree(BFS)
- HDU 4275 Color the Tree(哈希+树同构+组合数学+树形dp)
- hdu-4718:The LCIS on the Tree(树链剖分+区间合并)
- HDU 1561 The more, The Better / 树形DP
- HDU - 5834 Magic boy Bi Luo with his excited tree 树形dp 好题~
- HDU 4912 Paths on the tree 贪心+lca
- 【树形DP】【HDU 4276】The Ghost Blows Light
- 多校北邮现场赛(bupt 196 cc on the tree 搜索叶结点间的最短路 DFS)