1021 Deepest Root
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 Error: K components where K is the number of connected components in the graph.
在图中找构造出最长树的根结点,若不止一个连通分量则输出连通分量个数。
思路:在图中随意找一个结点进行第一次dfs,若只有一个连通分量,则找到最长子树一端的根结点,再找取这些结点中的一个进行第二次dfs,就可以找到另一端的根节点。
#include <iostream>
#include <string>
#include<algorithm>
#include<vector>
#include<utility>
#include<set>
#include<math.h>
using namespace std;
const int MAXSIZE = 10010;
const int MAX = 0x3fffffff;
int N, C, K, Q;
int visited[MAXSIZE] = { false };
vector<int> temp;
vector<vector<int> > v;
int maxheight = 0;
set<int> s;
void DFS(int vex, int height)
{
if (height > maxheight)
{
temp.clear();
temp.push_back(vex);
maxheight = height;
}
else
if (height == maxheight)
temp.push_back(vex);
visited[vex] = true;
for (int i = 0; i < v[vex].size(); i++)
{
if (!visited[v[vex][i]])
DFS(v[vex][i], height + 1);
}
}
int main()
{
int v1, v2;
int s1,cnt=0;
cin >> N;
v.resize(N + 1);
for (int i = 0; i < N - 1; i++)
{
cin >> v1 >> v2;
v[v1].push_back(v2);
v[v2].push_back(v1);
}
for (int i = 1; i <= N; i++)
{
if (!visited[i])
{
DFS(i, 1);
if (i == 1)
{
if (!temp.empty())s1 = temp[0];
for (int i = 0; i < temp.size(); i++)
s.insert(temp[i]);
}
cnt++;
}
}
if (cnt != 1)
cout << "Error: " << cnt << " components";
else
{
temp.clear();
maxheight = 0;
fill(visited, visited + N + 1, false);
DFS(s1, 1);
for (int i = 0; i < temp.size(); i++)
s.insert(temp[i]);
for (auto& a : s)
{
cout << a << endl;
}
}
return 0;
}