1021 Deepest Root (25 分)(经典搜索)
1021 Deepest Root (25 分)A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root. Input Specification:Each input file contains one test case. For each case,the first line contains a positive integer N (≤10?4??) which is the number of nodes,and hence the nodes are numbered from 1 to N. Then N?1 lines follow,each describes an edge by given the two adjacent nodes‘ numbers. Output Specification:For each test case,print each of the deepest roots in a line. If such a root is not unique,print them in increasing order of their numbers. In case that the given graph is not a tree,print Sample Input 1:5 1 2 1 3 1 4 2 5 Sample Output 1:3 4 5 Sample Input 2:5 1 3 1 4 2 5 3 4 Sample Output 2:Error: 2 components #include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<queue> #include<set> #include<algorithm>
using namespace std; const int maxn=1e4+10; vector<int>v[maxn]; vector<int>g[maxn]; set<int>s; set<int>::iterator it; int f[maxn]; int n,x,y; int book[maxn]; int vis[maxn],ans[maxn]; void init() { for(int i=1;i<maxn;i++) f[i]=i; } int getf(int x) { return f[x]==x?x:f[x]=getf(f[x]); } void merge(int x,int y) { int tx=getf(x); int ty=getf(y); if(tx!=ty) f[tx]=ty; } int bfs(int x) { int high=1; queue<int>q; g[high].push_back(x); q.push(x); vis[x]=1; while(!q.empty()) { int sum=q.size(); high++; for(int i=0;i<sum;i++) { int head=q.front(); q.pop(); for(int j=0;j<v[head].size();j++) { if(vis[v[head][j]]) continue; vis[v[head][j]]=1; g[high].push_back(v[head][j]); q.push(v[head][j]); } } } return high-1; } void dfs(int x) { book[x]=1; for(int i=0;i<v[x].size();i++) { if(!book[v[x][i]]) { book[v[x][i]]=1; dfs(v[x][i]); } } } int main() { cin>>n; //init();
for(int i=0;i<n-1;i++) { scanf("%d%d",&x,&y); // merge(x,y);
v[x].push_back(y); v[y].push_back(x); } int cnt=0; for(int i=1;i<=n;i++) { if(!book[i]) { dfs(i); cnt++; } } /* for(int i=1;i<=n;i++) { if(f[i]==i) cnt++; }*/
if(cnt!=1) { printf("Error: %d componentsn",cnt); return 0; } int high=bfs(1); cnt=0; for(int i=0;i<g[high].size();i++) { s.insert(g[high][i]); ans[cnt++]=g[high][i]; } for(int i=0;i<maxn;i++) g[i].clear(); memset(vis,0,sizeof(vis)); high=bfs(ans[0]); for(int i=0;i<g[high].size();i++) s.insert(g[high][i]); for(it=s.begin();it!=s.end();it++) cout<<(*it)<<endl; return 0; }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- linux – 有没有办法将两个实例化的systemd服务作为一个单元
- redhat – 如何在Red Hat Enterprise Linux上配置永久arp条
- linux – 将Python Web(Tornado)应用程序部署到多个服务器
- linux – 如何使用unix脚本发送带有消息的邮件
- linux – bash – 用引号括起所有数组元素或参数
- Linux环境中的实用程序`memhog`的详细信息?
- linux – 用于Mac 10.7.1的LDAP用户管理工具
- Linux:读取文件需要多少磁盘I / O?如何最小化?
- sudo – 如何使用tty运行特使任务?
- linux – Ubuntu Device-mapper似乎无敌!