SPOJ GCPC11J Time to live(求一棵树的直径(两个BFS))
2015-07-21 23:04
274 查看
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=83468#problem/D
题意:给出一棵树,让你找出一个节点,使得所有点到这个节点的最大距离最小
分析:可以想到,若是找到这棵树的最大深度length,再除2,即是结果,若是length是奇数,ans+1; 也可以 (length+1)/2,不管奇数偶数。
题意:给出一棵树,让你找出一个节点,使得所有点到这个节点的最大距离最小
分析:可以想到,若是找到这棵树的最大深度length,再除2,即是结果,若是length是奇数,ans+1; 也可以 (length+1)/2,不管奇数偶数。
#include <iostream> #include <stdio.h> #include <math.h> #include <algorithm> #include <queue> #include <stack> #include <vector> #include <string> #include <string.h> #include <map> #include <set> using namespace std; #define maxn 100005 #define inff 1000000000 vector<int>v[maxn]; int f[maxn]; struct node { int x,s; }tx,ty; int l; int bfs(int x) { queue<node>q; int i,len,ans=-inff; tx.x=x; tx.s=0; q.push(tx); f[tx.x]=1; while(!q.empty()) { tx=q.front(); q.pop(); if(tx.s>ans) { ans=tx.s; l=tx.x; } f[tx.x]=1; len=v[tx.x].size(); for(i=0;i<len;i++) { ty.x=v[tx.x][i]; ty.s=tx.s+1; if(f[ty.x]==0) q.push(ty); } } return ans; } int main() { int t,i,n,x,y; cin>>t; while(t--) { cin>>n; for(i=0;i<maxn;i++) v[i].clear(); for(i=1;i<n;i++) { cin>>x>>y; v[x].push_back(y); v[y].push_back(x); } memset(f,0,sizeof f); int ans1=bfs(0); memset(f,0,sizeof f); int ans2=bfs(l); cout<<(max(ans1,ans2)+1)/2<<endl; } return 0; }
相关文章推荐
- c++ 名词空间
- 网页屏蔽右击或者添加右键菜单
- 使用微软的(how-old.net)构建智能门店管理系统
- Mysql 环境配置查询
- [Android] Service服务详解以及如何使service服务不被杀死
- Selenium学习笔记之007:定位一组元素
- iOS-CALayer实现简单进度条
- iOS开发中关于nslog的几种流行做法小结
- 云时代的分布式数据库:阿里分布式数据库服务DRDS
- MongoDB客户端shell基本操作
- python系列------输入输出
- 股票学习(财务分析15)
- 二分查找算法
- A Simple OpenGL Shader Example II
- A*搜索算法
- 阿里云分布式缓存OCS与DB之间的数据一致性
- 迅雷影音提取剪辑视频音频
- MySQL进阶---MySql常用命令总结
- s3c2440锁相环
- 温故知新,基础复习(二叉堆排序)