版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题目大意:给出一个无环联通图,找到最长通路的端点。
做这题…要注意别拼错单词。
首先使用一次DFS算法,找到深度最大点中的一个最大点,然后再以这个最大点为起点,再次DFS出其他的最大点,由此得到所有的最大点。
#include<cstdio>
#include<set>
#include<vector>
#include<iostream>
#include <algorithm>
using namespace std;
int maxheight = 0, n;
vector<vector<int> > v;
bool visit[10010];
set<int> s;
vector<int> temp;
void DFS(int node, int height) {
if (height > maxheight) {
temp.clear();
temp.push_back(node);
maxheight = height;
}else if (height == maxheight) {
temp.push_back(node);
}
visit[node] = true;
for (int i = 0; i < v[node].size(); i++) {
if (visit[v[node][i]] == false)
DFS(v[node][i], height + 1);
}
}
将深度最大点存入vector中。
在主函数中,DFS的同时顺便统计连通分量。
int main() {
scanf("%d", &n);
v.resize(n + 1);
int count = 0, s1 = 0, a, b;
for (int i = 0; i < n - 1; i++) {
scanf("%d%d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
}
for (int i = 1; i <= n; i++) {
if (visit[i] == false) {
DFS(i, 1);
if (i == 1) {
if (temp.size()!=0) s1 = temp[0];
for (int j = 0; j < temp.size(); j++)
s.insert(temp[j]);
}
count++;
}
}
if (count >1)
printf("Error: %d components", count);
else {
temp.clear();
fill(visit, visit + 10010, false);
maxheight = 0;
DFS(s1, 1);
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);
}
return 0;
}