#include<bits/stdc++.h>
using namespace std;
const int MAXV=10010;
int G[MAXV][MAXV]={0};
bool vis[MAXV]={false};
int n;
int cnt=0;
vector<int> temp;
int maxdepth=0;
set<int> st;
int tt;
void dfs(int u,int depth){
vis[u]=true;
if(maxdepth<depth){
temp.clear();
temp.push_back(u);
maxdepth=depth;
}else if(maxdepth==depth){
temp.push_back(u);
}
for(int v=1;v<=n;v++){
if(vis[v]==false&&G[u][v]==1){
dfs(v,depth+1);
}
}
}
void dfstra(){
for(int i=1;i<=n;i++){
if(vis[i]==false){
dfs(i,1);
cnt++;
if(temp.size()!=0) tt=temp[0];
for(int j=0;j<temp.size();j++)
st.insert(temp[j]);
}
}
}
int main()
{
freopen("in.txt","r",stdin);
cin>>n;
for(int i=0;i<n-1;i++){
int start,end;
cin>>start>>end;
G[start][end]=1;
G[end][start]=1;
}
dfstra();
if(cnt>1){
cout<<"Error: "<<cnt<<" components";
}else if(cnt==1){
temp.clear();
fill(vis, vis + 10010, false);
maxdepth=0;
dfs(tt,1);
for(int i=0;i<temp.size();i++){
st.insert(temp[i]);
}
for(auto it=st.begin();it!=st.end();it++){
cout<<*it<<endl;
}
}
return 0;
}
调试的第一个例子的过程中会发现一次dfstra就会遍历所有节点,此时temp里面只有一个5,是局部最优解,也就是以1为根节点的时候的最优解,为了找到全局最优解,就要以这个局部最优解为根节点在进行一次dfs遍历。
//暴力做了一遍,发现会内存超限,这是个注意点...
后来修改了一下,把INF改成0就ok了,暴力也能的大部分分数
邻接表会超内存,那么问题来了,当时我是怎么拿这段代码过的pat。。。