【HDU】2196 Computer 树形dp
来源:互联网 发布:淘宝怎么搜军刺 编辑:程序博客网 时间:2024/05/17 01:23
题目传送门
博主暴走中……神他妈的HDU,不能用fread读入的!!!我因为这个错WA了10+发……
这题的题意就是求每一个节点在树上和它距离最大的点的距离。
其实这题的思路还是挺清晰的,我们可以对于一棵有根树的一个非根非叶子节点进行讨论。
这个节点的最大距离有两种情况,一种是从以该节点为根的子树的最大距离扩展过来,另一种就是从父亲节点扩展过来。
引用一下另一位大佬的图片(看2号节点):
对于从父亲节点扩展过来的情况,我们还要分类讨论,若父亲节点的最大距离不是从当前节点扩展过来,那么当前节点的答案就是max(父亲节点的最大距离+父亲节点到当前节点的距离,当前节点的最大距离);若父亲节点的最大距离是从当前节点扩展过来,那么当前节点的答案就是max(父亲节点的第二大距离(不是从当前节点扩展来的)+父亲节点到当前节点的距离,当前节点的最大距离)。最后递归求解即可。
可能写的有点恶心,望读者能耐心读完吧。
附上AC代码:
#include <cstdio>#include <cctype>#include <cstring>#include <algorithm>#define N 10010using namespace std;struct side{int to,w,nt;}s[N<<1];int n,num,h[N],y,w,f[N][3];/*inline char nc(){static char ch[100010],*p1=ch,*p2=ch;return p1==p2&&(p2=(p1=ch)+fread(ch,1,100010,stdin),p1==p2)?EOF:*p1++;}inline void read(int &a){static char c=nc();int f=1;for (;!isdigit(c);c=nc()) if (c=='-') f=-1;for (a=0;isdigit(c);a=a*10+c-'0',c=nc());a*=f;return;}*/inline void add(int x,int y,int w){s[num]=(side){y,w,h[x]},h[x]=num++;}inline void so1(int x){for (int i=h[x]; i!=-1; i=s[i].nt){so1(s[i].to);int tmp=f[s[i].to][0]+s[i].w;if (tmp>=f[x][0]) f[x][1]=f[x][0],f[x][0]=tmp;else if (tmp>f[x][1]) f[x][1]=tmp;}return;}inline void so2(int x){for (int i=h[x]; i!=-1; i=s[i].nt){if (f[x][0]==f[s[i].to][0]+s[i].w) f[s[i].to][2]=max(f[x][1],f[x][2])+s[i].w;else f[s[i].to][2]=max(f[x][0],f[x][2])+s[i].w;so2(s[i].to);}return;}int main(void){while (~scanf("%d",&n)){memset(h,-1,sizeof(h)),num=0;for (int i=2; i<=n; ++i) scanf("%d%d",&y,&w),add(y,i,w);memset(f,0,sizeof(f)),so1(1),so2(1);for (int i=1; i<=n; ++i) printf("%d\n",max(f[i][0],f[i][2]));}return 0;}
阅读全文
0 0
- HDU 2196 Computer(树形dp)
- 【树形DP】 HDU 2196 Computer
- HDU 2196 Computer(树形DP)
- Hdu 2196 Computer(树形dp)
- Computer - HDU 2196 树形dp
- Hdu 2196 Computer (树形dp)
- HDU 2196 Computer | 树形dp
- 【树形DP】 HDU 2196 Computer
- HDU 2196 Computer (树形DP)
- hdu 2196 Computer (树形dp)
- *HDU 2196 - Computer(树形DP)
- [HDU 2196] Computer 树形dp
- HDU 2196Computer 树形dp
- 【hdu】2196 Computer【树形dp】
- HDU 2196 Computer [树形dp]
- hdu 2196 Computer(树形DP)
- 树形DP-HDU-2196-Computer
- 【HDU】2196 Computer 树形dp
- Python学习01-中文编码
- 自适应控制 PID
- html<head>
- nginx对ip限流的操作
- Websphere SRVE8111E
- 【HDU】2196 Computer 树形dp
- 【I2C时序分析】-hym8563为列
- Xcode 下删除Provisioning Profiles文件详细介绍
- |BZOJ 1650|二分|贪心|[Usaco2006 Dec]River Hopscotch 跳石子
- 程序中调用进程API时进程打开缓慢引起方法调用失败
- JS组件系列——表格组件神器:bootstrap table(三:终结篇,最后的干货福利)
- bzoj 3029: 守卫者的挑战 概率dp
- cordova app 升级
- 简易拼图(OC)