题目
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 ( ≤ 1 0 4 ) N (\le10^4) N(≤104) which is the number of nodes, and hence the nodes are numbered from 1 to N N N. Then N − 1 N−1 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
题目大意
给定一个图,先判断这个图是否是一棵树,在求出树的最大高度,输出最大高度那条路径的根节点
思路
- 由于给出边数为
N-1
(最小生成树),故只需要判断图是否连同即可,若连同就是一棵树,若不连同输出连同分量个数,采用深度优先遍历即可; - 求最大高度对应的根节点,先任取一点作为根节点,遍历得到最大高度的尾结点的集合 A A A,再在 A A A中任取一点作为根节点,遍历得到最大高的尾结点的集合 B B B, A 、 B A、B A、B的并集即为答案(这里要仔细推敲一下),还有一点要弄明白,树的任一节点都可以作为根节点,也就是说最大高度所对应的根节点和尾结点是等价的(都可为根节点,都可为尾结点)
该题有一个坑点,不能用矩阵存储树,内存回爆( 1 0 4 10^4 104),应该用邻接链表存储
代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
using namespace std;
struct node{
int data;
node *next;
};
struct root{
node *next;
};
int n;
vector<root> v;
vector<int> visited;
vector<int> tmp;
int maxdeep = 0;
void dfs(int s, int deep){
if(deep > maxdeep){
tmp.clear();
maxdeep = deep;
tmp.push_back(s);
}
if(deep == maxdeep)
tmp.push_back(s);
visited[s] = true;
node *p = v[s].next;
while(p){
if(!visited[p->data])
dfs(p->data, deep+1);
p = p->next;
}
}
int main(){
scanf("%d", &n);
v.resize(n+1);
visited.resize(n+1, 0);
for(int i=1; i<=n; i++)
v[i].next = NULL;
for(int i=0; i<n-1; i++){
int a, b;
scanf("%d%d", &a, &b);
node *p = new node;
node *q = new node;
p->data = b;
p->next = v[a].next;
v[a].next = p;
q->data = a;
q->next = v[b].next;
v[b].next = q;
}
int co = 0;
for(int i=1; i<=n; i++){
if(!visited[i]){
co++;
dfs(i, 1);
}
}
if(co > 1)
printf("Error: %d components\n", co);
else{
set<int> ans;
for(int j=0; j<tmp.size(); j++)
ans.insert(tmp[j]);
for(int i=1; i<=n; i++)
visited[i] = false;
dfs(tmp[0], 1);
for(int j=0; j<tmp.size(); j++)
ans.insert(tmp[j]);
for(set<int>::iterator it=ans.begin(); it!=ans.end(); it++)
printf("%d\n", *it);
}
return 0;
}