先判断有几个连通块吗,因为已经满足边的个数等于顶点个数减1所以一定是一棵树,只要是1.
本来用的是优先队列,最后发现没过,其实是Error: K components 少了个s看题目一定要仔细
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 10100;
vector<int> G[MAXN];
int maxdepth = -1;
priority_queue<int,vector<int>,greater<int>> depthRoot;
bool vis[MAXN];
vector<int> temp;
set <int> s;
int happen[MAXN];
int n;
int root;
void DFS(int u,int depth)
{
vis[u] = true;
if(depth > maxdepth)
{
maxdepth = depth;
temp.clear();
temp.push_back(u);
}
else if(depth == maxdepth)
{
temp.push_back(u);
}
for(int i = 0;i<G[u].size();i++)
{
if(vis[G[u][i]] == false)
{
DFS(G[u][i],depth + 1);
}
}
}
int main(void)
{
freopen("pat0314/in.txt","r",stdin);
cin>>n;
for(int i = 0;i<n - 1;i++)
{
int l,r;
cin>>l>>r;
G[l].push_back(r);
G[r].push_back(l);
}
int num = 0;
int s1 = 0;
fill(vis,vis + MAXN,false);
for(int i = 1;i<=n;i++)
{
if(vis[i] == false)
{
num++;
DFS(i,0);
if(i == 1)
{
if(temp.size() != 0)
{
s1 = temp[0];
}
for(int k = 0;k<temp.size();k++)
{
s.insert(temp[k]);
}
}
}
}
if(num == 1)
{
temp.clear();
fill(vis,vis + MAXN,false);
maxdepth = -1;
DFS(s1,0);
for(int i = 0;i<temp.size();i++)
{
s.insert(temp[i]);
}
for(auto it = s.begin(); it != s.end(); it++)
printf("%d\n", *it);
}
else
{
printf("Error: %d components",num);
return 0;
}
return 0;
}