注:要考虑时间空间效率问题:使用邻接表,并减少使用dfs的次数(原来为n次dfs,后面改为2次)。
#include <stdio.h>
#include <string.h>
#include <deque>
#include <algorithm>
using namespace std;
int n;
deque<int> map[10001];
int set[10001];
void dfsTraverse(int t, int h, int &maxh, deque<int> &maxhIndex);
int main(int argc, char *argv[]) {
scanf("%d", &n);
int i, j, k;
int a, b;
for(i = 0; i < n - 1; i++) {
scanf("%d %d", &a, &b);
map[a].push_back(b);
map[b].push_back(a);
}
memset(set, -1, 10001 * sizeof(int));
for (i = 1; i <= n; i++) {
if (set[i] < 0 && !map[i].empty()) {
for (j = 0; j < map[i].size(); j++) {
int p = map[i][j];
while (set[p] >= 0) p = set[p];
if (p != i) {
set[i] += set[p];
set[p] = i;
}
}
}
}
int count = 0;
for (i = 1; i <= n; i++) {
if (set[i] < 0) count++;
}
if (count > 1) {
printf("Error: %d components\n", count);
return 0;
}
int maxDepth = 0;
int depth = 0;
deque<int> maxhIndex;
maxhIndex.clear();
memset(set, 0, 10001 * sizeof(int));
dfsTraverse(1, 0, depth, maxhIndex);
int start = maxhIndex.front();
deque<int> d(maxhIndex);
memset(set, 0, 10001 * sizeof(int));
maxhIndex.clear();
dfsTraverse(start, 0, depth, maxhIndex);
for (i = 0; i < d.size(); i++)
maxhIndex.push_back(d[i]);
sort(maxhIndex.begin(), maxhIndex.end());
printf("%d\n", maxhIndex[0]);
for (i = 1; i < maxhIndex.size(); i++)
if (maxhIndex[i] != maxhIndex[i - 1])
printf("%d\n", maxhIndex[i]);
return 0;
}
void dfsTraverse(int t, int h, int &maxh, deque<int> &maxhIndex) {
set[t] = 1;
if (h > maxh) {
maxh = h;
maxhIndex.clear();
maxhIndex.push_back(t);
} else if (h == maxh) {
maxhIndex.push_back(t);
}
for (int i = 0; i < map[t].size(); i++) {
if (set[map[t][i]] == 0)
dfsTraverse(map[t][i], h + 1, maxh, maxhIndex);
}
return;
}