这道题的解法是参考一本算法书给出的,先用DFS或者并查集找寻连通分量的个数,个数不为一则输出结果,个数为一的话就按照这样的思路:先任意选择一个结点,从该结点开始遍历整棵树,获取能达到的最深的顶点,记录为集合A。然后从集合A中任意一个结点出发遍历整棵树,获取能达到的最深的顶点,记录为集合B。可以证明集合A与集合B的并集即为所求的使树高最大的根节点,具体过程可以自己查阅。
并查集版本
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector <int>g[10005];
int father[10005];
int n;
int block ;
int v[10005];
int maxh =0;
vector<int>result,first;
void init()
{
for(int i =0;i<=n;i++)
father[i] = i;
for(int i=0;i<=n;i++)
v[i] = 0;
block = 0;
}
int findfather(int x)
{
int temp = x;
while(x!=father[x])
x =father[x];
while (father[temp]!=temp)
{
int z = temp;
temp =father[temp];
father[z] = x;
}
return x;
}
void union0(int x,int y)
{
int fx = findfather(x);
int fy = findfather(y);
if(fx!=fy)father[fx] = fy;
}
void dfs(int n,int height,int pre)
{
if(height>maxh)
{
first.clear();
first.push_back(n);
maxh = height;
}
else if(height==maxh)
{
first.push_back(n);
}
for(int i = 0 ;i<g[n].size();i++)
{
if(g[n][i]==pre)continue;
else
dfs(g[n][i],height+1,n);
}
}
int main()
{
cin>>n;
init();
for(int i =0;i<n-1;i++)
{
int x,y;
cin>>x>>y;
g[x].push_back(y);
g[y].push_back(x);
union0(x,y);
}
for(int i =1;i<=n;i++)
{
int findf = findfather(i);
if(v[findf]==0)
{
v[findf]=1;
block++;
}
}
if(block>1)
cout<<"Error: "<<block<<" components"<<endl;
else
{
dfs(1,1,-1);
result = first;
maxh = 0;
dfs(first[0],1,-1);
for(int i = 0;i<first.size();i++)
result.push_back(first[i]);
sort(result.begin(),result.end());
cout<<result[0]<<endl;
for(int i =1;i<result.size();i++)
if(result[i]!=result[i-1])cout<<result[i]<<endl;
}
return 0;
}
DFS版本
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
vector<int> g[10005];
int n;
int block;
int v[10005];
int maxh = 0;
vector<int> result, first;
void dfs(int n, int height, int pre)
{
if (height > maxh)
{
first.clear();
first.push_back(n);
maxh = height;
}
else if (height == maxh)
{
first.push_back(n);
}
for (int i = 0; i < g[n].size(); i++)
{
if (g[n][i] == pre)
continue;
else
{
dfs(g[n][i], height + 1, n);
}
}
}
void dfss(int n)
{
for (int i = 0; i < g[n].size(); i++)
{
if (v[g[n][i]] == 0)
{
v[g[n][i]] = 1;
dfss(g[n][i]);
}
}
return;
}
int main()
{
cin >> n;
for (int i = 0; i < n - 1; i++)
{
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
//union0(x,y);
}
memset(v, 0, sizeof(v));
for (int i = 1; i <= n; i++)
{
if (v[i] == 1)
continue;
else
{
dfss(i);
block++;
}
}
if (block > 1)
cout << "Error: " << block << " components" << endl;
else
{
dfs(1, 1, -1);
result = first;
maxh = 0;
dfs(first[0], 1, -1);
for (int i = 0; i < first.size(); i++)
result.push_back(first[i]);
sort(result.begin(), result.end());
cout << result[0] << endl;
for (int i = 1; i < result.size(); i++)
if (result[i] != result[i - 1])
cout << result[i] << endl;
}
return 0;
}