自己第一次写36行写完了,感觉很简单。一提交测试点3超时,然后想办法在DFS里面剪枝,但是并没有什么用。然后就去看了一下柳神的代码,才知道一个结论。
第一次DFS记录最远节点(它一定是全局最远的),然后再用其中一个再DFS一次。
应该是你局部的最远路径,那么一定是全局最远的一个子路径。
#include <bits/stdc++.h>
using namespace std;
int n, a, b, cnt = 0, cmpt = 1, maxH = 0, flag = 0;
struct node {
int r, t;
};
set<int> ans;
vector<vector<int>> v;
vector<int> temp;
bool visD[10010], vis[10010];
void DFS (int r, int h) {
cnt++;
visD[r] = true;
vis[r] = true;
if (h > maxH) {
temp.clear();
temp.push_back(r);
maxH = h;
}
else if (h == maxH) {
temp.push_back(r);
}
for (int i = 0; i < v[r].size(); i++) {
int now = v[r][i];
if (vis[now] == true) continue;
DFS (now, h + 1);
}
}
int main() {
scanf ("%d", &n);
v.resize(n + 1);
for (int i = 0; i < n - 1; i++) {
scanf ("%d %d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
}
DFS (1, 0);
for (int i = 1; i <= n; i++) {
// cout << visD[i] << endl;
if (visD[i] == false) {
cmpt++;
DFS (i, 0);
}
}
if (cmpt >= 2) printf ("Error: %d components", cmpt);
else {
fill (vis, vis + 10010, false);
for (auto it : temp) ans.insert(it);
DFS (temp[0], 0);
for (auto it : temp) ans.insert(it);
}
for (auto it : ans) printf ("%d\n", it);
}