1021. Deepest Root (25)
2017-01-25 19:02
190 查看
1021. Deepest Root (25)
时间限制1500 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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:
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>
using namespace std;
struct G{
int node;
G* Next;
} graph[10001];
int count=0;
struct disj{
int no;
disj* father;
}dis[10001];
disj* find(disj* a){
if(a->father!=NULL)
return a->father=find(a->father);
else
return a;
}
void unino(disj* a,disj* b){
if(find(a)==find(b))
count++;
else
a->father=b;
}
void add(int a,int b){
G* t=&graph[a];
G* te;
while(t->Next!=NULL){
t=t->Next;
if(t->node==b)
return;
}
if(a>b)
unino(&dis[a],&dis[b]);
te=new G;
te->Next=NULL;
te->node=b;
t->Next=te;
}
int isread[10001];
int DFS(int a,int N){
isread[a]=1;
G* t=&graph[a];
int max=-1,v;
while(t->Next!=NULL){
t=t->Next;
if(isread[t->node]==0){
v=DFS(t->node,N);
if(v>max)
max=v;
}
}
return max+1;
}
int main(){
int N,max=-1;
cin>>N;int j;
int *h=new int
;
int i,temp1,temp2,temp3;
for(i=0;i<10001;i++){
graph[i].Next=NULL;
graph[i].node=i;
dis[i].father=NULL;
dis[i].no=i;
}
for(i=0;i<N-1;i++){
cin>>temp1>>temp2;
add(temp1,temp2);
add(temp2,temp1);
}
if(count!=0){
cout<<"Error: "<<count+1<<" components";
return 0;
}
for(i=1;i<N+1;i++){
h[i]=-1;
if(graph[i].Next!=NULL&&graph[i].Next->Next==NULL){
for(j=1;j<N+1;j++)
isread[j]=0;
h[i]=DFS(i,N);
}
if(h[i]>max)
max=h[i];
}
for(i=1;i<N+1;i++){
if(h[i]==max)
cout<<i<<endl;
}
}
感想:1.判断联通环的个数,只要判断某项中两点都已经出现过的次数即可,数组即可实现,我只是为了复习一下并查集。
2。算深度建议用DFS,我也想到了给每个边一个值,初始值为0,每次加入一条边就用DFS给能增加深度的点深度+1,直接DFS更加简便,而且其实只要对只有一条边的点进行DFS就可以了。
相关文章推荐
- 斐波那契数列 Java实现
- mysql客户端工具
- 三星事件调查结果新鲜奉上 全球多家媒体共同出席发布会
- NYOJ100 - 1的个数
- SPOJ - PUTNIK(想法+dp,好题)
- 我与虚拟机的初次接触及初探Liux命令 20155338
- Qt for Windows:Qt 5.8.0 MinGW 静态编译版本(包含OpenSSL)
- android面试笔试题详解
- 嵌入式Linux-内存管理基础
- codevs4373&洛谷1866 滑动窗口
- 实现shell四则运算
- java生成和操作Excel文件
- 1039. 到底买不买(20)
- leetcode--100. Same Tree
- Stanford NER CRF FAQ
- NUCLEO-F042K6驱动的彩色灯环(WS2812)
- NYOJ31 - 5个数求最值
- 多重背包模板--二进制优化模板&&单调队列优化模板
- Android必学之AsyncTask
- 阿里 JAVA 开发手册 学习 4 工程规约