PAT 1021 Deepest Root (25)
1021 Deepest Root (25)(25 分)
A graph which is connected and acyclic can be considered a tree. The hight 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.
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個點n-1條邊的無向圖如果是連通圖就一定是樹,如果不連通就勢必有環,但凡有一個環就會多一個連通分支,所以只要求出環的個數,連通分支數就是環的個數+1。然後如果是樹,這個問題就成了求樹的直徑(最長的簡單路),選取任意一點a先做一遍dfs,求出距離該點最遠的點集合A,再從該集合中任選一點b再做一遍dfs,求出距離最遠的點集合B,答案就是集合A、B的並集。
程式碼:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <climits>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
vector<vector<int>> g;
vector<int> v;
set<int> s;
int vis[10005], maxd = 0;
void dfs(int x, int depth)
{
vis[x] = 1;
if (depth > maxd)
{
maxd = depth;
v.clear();
v.push_back(x);
}
else if (depth == maxd)
v.push_back(x);
for (int i = 0; i < g[x].size(); i++)
{
if (!vis[g[x][i]])
dfs(g[x][i], depth + 1);
}
}
int main()
{
int n, cnt = 1;
cin >> n;
g.resize(n + 1);
memset(vis, 0, sizeof(vis));
for (int i = 1; i < n; i++)
{
int from, to;
cin >> from >> to;
g[from].push_back(to);
g[to].push_back(from);
if (vis[from] && vis[to])
cnt++;
else
vis[from] = vis[to] = 1;
}
if (cnt > 1)
cout << "Error: " << cnt << " components" << endl;
else
{
memset(vis, 0, sizeof(vis));
dfs(1, 1);
for (int i = 0; i < v.size(); i++)
s.insert(v[i]);
v.clear();
maxd = 0;
memset(vis, 0, sizeof(vis));
dfs(*s.begin(), 1);
for (int i = 0; i < v.size(); i++)
s.insert(v[i]);
for (set<int>::iterator iter = s.begin(); iter != s.end(); iter++)
cout << *iter << endl;
}
return 0;
}