NCPC2015 A Adjoin the Networks(求树的直径)
来源:互联网 发布:典型数据报表图片 编辑:程序博客网 时间:2024/06/03 22:41
题意:给出很多个树,让你连接最少的边使整个图的直径最短。
思路:对每个树求出树的半径,然后将半径最大的树放在中间,然后将其他的树连接这个半径最大的树,求出ans即可。注意细节!
#include <iostream>#include<string.h>#include<vector>#include<queue>#include<algorithm>#include<stdio.h>#include<math.h>#include<map>#include<stdlib.h>#include<time.h>using namespace std;typedef long long ll;const int N=100010;int head[N];int ip;struct edgenode{ int to; int next;} tu[N*2];void init(){ ip=0; memset(head,-1,sizeof(head));}void add(int u,int v){ tu[ip].to=v,tu[ip].next=head[u],head[u]=ip++;}bool vis[N]= {0};int ans[105000];int st,ed,len;void dfs(int now,int pre,int sum){ vis[now]=1; if(sum>len)len=sum,st=now; for(int k=head[now]; k!=-1; k=tu[k].next) { int to=tu[k].to; if(to!=pre) dfs(to,now,sum+1); }}int main(){ int n,l; init(); scanf("%d%d",&n,&l); for(int i=0; i<l; i++) { int a,b; scanf("%d%d",&a,&b); add(a,b); add(b,a); } int bj=0; for(int i=0; i<n; i++) if(!vis[i]) { len=0; st=i; dfs(i,-1,0); ed=st; len=0; dfs(st,-1,0); ans[bj++]=len; } sort(ans,ans+bj); if(bj>=3) { int hh; hh=max(ans[bj-1],(ans[bj-1]+1)/2+(ans[bj-2]+1)/2+1); hh=max(hh,(ans[bj-2]+1)/2+(ans[bj-3]+1)/2+2); printf("%d\n",hh); } else if(bj==2) { int hh=max(ans[1],(ans[0]+1)/2+(ans[1]+1)/2+1); printf("%d\n",hh); } else printf("%d\n",ans[0]); return 0;}
0 0
- NCPC2015 A Adjoin the Networks(求树的直径)
- 2015-2016 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2015) Adjoin the Networks (树的直径)
- CodeFroces gym 100781 A.Adjoin the Networks(贪心)
- CSU 1681 Adjoin(树形dp && 树的直径)
- NCPC 2015 A Adjoin the Networks(好题)
- 求树的直径
- 求树的直径
- 求树的直径
- 求树的直径
- 求树的直径(poj1383验证)
- 求树的直径(最长路径)
- leetcode 刷题(求树的直径)
- poj2631 Roads in the North(求树的直径裸题)
- BFS求树的直径
- HDU4607(求树的直径)
- [toj3517]【求树的直径】
- 求树的直径证明
- hdu4607 (求树的直径)
- AndroidStudio中使用Git发布与更新,同步到本地(github关联)
- Java—序列化—Serializable—Externalizable
- js学习笔记:script元素
- 计步器
- hdu 2108 Shape of HDU
- NCPC2015 A Adjoin the Networks(求树的直径)
- 使用NSFileManager枚举目录种的内容(遍历目录)
- 前端学习之路——盒子模型练习
- 序列相关
- poj1270 Following Orders
- 丑数(空间换时间)
- 【EmbeddedDev】搭建你的BeagleBot遥控车
- 外网访问本机工具花生壳和ngrok
- Linux系统中“动态库”和“静态库”那点事儿