PAT 1021. Deepest Root (25)
来源:互联网 发布:华腾软件学院 编辑:程序博客网 时间:2024/05/25 21:34
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 (<=10000) 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 "Error: K components" where K is the number of connected components in the graph.
Sample Input 1:51 21 31 42 5Sample Output 1:
345Sample Input 2:
51 31 42 53 4Sample Output 2:
Error: 2 components
#include <cstdio>#include<string.h>#include<string>#include<map>#include<vector>#include<stdio.h>#include<set>#include<iostream>#include <algorithm>using namespace std;vector<int> edge[10005];int mark[10005]={0};int deepest=-1;int path[10005];int p=0;int tmp;void dfs(int x,int deep){ mark[x]=1; if(deep>deepest) { deepest=deep; path[0]=x; p=1; } else if(deep==deepest) { path[p++]=x; } for(int i=0;i<edge[x].size();i++) { if(mark[edge[x][i]]==0) dfs(edge[x][i],deep+1); }}int main(){ int n; cin>>n; for(int i=1;i<n;i++) { int x,y; scanf("%d %d",&x,&y); edge[x].push_back(y); edge[y].push_back(x); } dfs(1,0); int flag=0; for(int i=1;i<=n;i++) if(mark[i]==0) {flag=1;break;} if(flag==1) { int cnt=1; for(int i=1;i<=n;i++) if(mark[i]==0) { cnt++;dfs(i,0); } printf("Error: %d components",cnt); } else { tmp=path[p-1]; set<int> S; for(int i=0;i<p;i++) S.insert(path[i]); p=0; memset(mark,0,sizeof(mark)); dfs(tmp,0); for(int i=0;i<p;i++) S.insert(path[i]); for(set<int>::iterator it=S.begin();it!=S.end();it++) { cout<<*it<<endl; } } return 0;}
- 1021. Deepest Root (25)-PAT
- PAT 1021. Deepest Root (25)
- PAT 1021. Deepest Root (25)
- PAT 1021. Deepest Root (25)
- PAT 1021. Deepest Root (25)
- PAT 1021. Deepest Root (25)
- 【PAT】1021. Deepest Root (25)
- pat 1021. Deepest Root (25)
- 【PAT】1021. Deepest Root (25)
- pat 1021. Deepest Root (25)
- PAT 1021. Deepest Root (25)
- PAT 1021. Deepest Root
- PAT 1021. Deepest Root
- pat 1021. Deepest Root
- PAT 1021. Deepest Root
- PAT 1021. Deepest Root
- 【PAT】1021. Deepest Root
- PAT 1021. Deepest Root
- (转载)对接【支付宝】支付接口
- 设计模式 ----- 单件模式
- 随机数生成
- 图像语义分割
- 开源大数据周刊-第67期
- PAT 1021. Deepest Root (25)
- Android获取View的宽度和高度
- Java设计模式之简单工厂模式
- 字节对齐的方法
- HGDB重建模板数据库的方法(适用于PG)
- 7 局部求和
- 美女头像这么多,他们用大数据告诉你哪个是骗子
- 搭建java环境\Tomcat安装和基本配置\Tomcat_MSM
- Windows中Django安装教程