1021 Deepest Root (25 point(s))
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 (≤104) 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:
5
1 2
1 3
1 4
2 5
Sample Output:
3
4
5
Sample Input:
5
1 3
1 4
2 5
3 4
Sample Output:
Error: 2 components
题目大意:
N 个节点 N-1 条边,若能构成一棵树,求具有最大深度时的所有根节点,按从小到大顺序;否则求连通分量数目
设计思路:
DFS
- DFS 求连通分量,若大于 1,直接输出连通分量数
- 若能构成树,再一次 DFS,寻找最大深度的根节点:
- 从第一次 DFS 得到的最大深度节点集合中,任选一个开始,再次得到一个最大深度节点的集合,两个节点集合的并集即为所求
编译器:C (gcc)
#include <stdio.h>
struct node {
int visit, level, depth;
struct adj *adj;
};
struct adj {
struct node *node;
struct adj *next;
};
struct temp {
int q[10000];
int c;
};
struct temp temp;
int maxheight;
void dfs(struct node *n, int height)
{
if (height > maxheight) {
temp.c = 0;
temp.q[temp.c] = n->level;
temp.c++;
maxheight = height;
} else if (height == maxheight) {
temp.q[temp.c] = n->level;
temp.c++;
}
struct adj *a;
for (a = n->adj; a; a = a->next) {
if (a->node->visit == 0)
dfs(a->node, height + 1);
}
}
int main(void)
{
int n, a, b;
struct node nodes[10000] = {0}, *pnode;
struct adj edges[20000] = {0}, *padj;
int i, count;
scanf("%d", &n);
for (i = 0; i < n; i++)
nodes[i].level = i;
for (i = 0; i < n - 1; i++) {
scanf("%d %d", &a, &b);
pnode = &nodes[a - 1];
padj = &edges[i * 2];
padj->node = &nodes[b - 1];
padj->next = pnode->adj;
pnode->adj = padj;
pnode = &nodes[b - 1];
padj = &edges[i * 2 + 1];
padj->node = &nodes[a - 1];
padj->next = pnode->adj;
pnode->adj = padj;
}
count = 0; maxheight = 0;
for (i = 0; i < n; i++) {
if (nodes[i].visit == 0) {
dfs(nodes + i, 1);
count++;
}
}
if (count > 1) {
printf("Error: %d components\n", count);
} else {
int num[10000] = {0};
for (i = 0; i < n; i++)
nodes[i].visit = 0;
for (i = 0; i < temp.c; i++)
num[temp.q[i]]++;
maxheight = 0; temp.c = 0;
dfs(nodes + temp.q[0], 1);
for (i = 0; i < temp.c; i++)
num[temp.q[i]]++;
for (i = 0; i < 10000; i++)
if (num[i])
printf("%d\n", i + 1);
}
return 0;
}