树的直径模板
来源:互联网 发布:网络割接方案 编辑:程序博客网 时间:2024/06/04 17:57
树的直径模板
http://codevs.cn/problem/1814/最长链.模板题
对于树上的最长链,有且仅有两种情况:
#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<cmath>using namespace std;int n,tot,a,b,ans,pos;int first[200010],nxt[200010];struct edge{ int u,v;}l[200010];void build(int f,int t){ l[++tot]=(edge){f,t}; nxt[tot]=first[f]; first[f]=tot;}void dfs(int k,int fa,int d){ if(d>ans) { ans=d; pos=k; } for(int i=first[k];i!=-1;i=nxt[i]) { int x=l[i].v; if(x==fa) continue; dfs(x,k,d+1); }}int main(){ memset(first,-1,sizeof(first)); scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d%d",&a,&b); if(a!=0) { build(i,a); build(a,i); } if(b!=0) { build(i,b); build(b,i); } } dfs(1,1,0);//第一遍DFS找出树上深度最深的点 ans=0; dfs(pos,1,0);//第二遍DFS由深度最深的点向上找最长链 printf("%d",ans); return 0; }
阅读全文
2 0
- 【模板】树的直径
- 树的直径模板
- 树的直径模板
- 树的直径(模板)
- TyvjP1520 树的直径(模板)
- 树的直径模板~~最长路径
- POJ1985Cow Marathon(求树的直径模板)
- poj 1985 树的直径模板题
- NOIP 冲刺 模板:树的直径
- 【原创】模板-树的前中后序遍历,树的重心直径
- HDU 2196 Computer(树的直径的模板题)
- 拓扑排序,树的直径模板(CF14D 枚举删边)
- POJ 1985--Cow Marathon【树的直径 && 模板】
- POJ 1985-Cow Marathon【树的直径模板】
- poj 1958 Cow Marathon(树的直径,模板题)
- poj 1985 Cow Marathon (树的直径 模板题)
- bzoj3124 [Sdoi2013]直径 树的直径
- 【模板】树的直径 DP (模板题:XJOI数字转换)
- git初始化
- MongoDB GUI( Robo 3T) Shell使用及操作
- 1.python及介绍
- linux ubuntu 14. 04下 OpenJdk7编译
- MFC复选框Checkbox
- 树的直径模板
- 正向代理与反向代理的区别
- 2.1.7出现异常的线程自动释放锁
- 利用一个portlet:resourceURL标签发送AJAX请求
- hdu 1025 Constructing Roads In JGShining's Kingdom
- 《Kotlin项目实战开发》 第4章 类与面向对象编程
- 数据结构(一)--ArrayList and LinkerList
- Matlab 对路径的操作及读写文件
- Android 必知必会