传送门
题意
给你一棵树,任取三个点,使得这三个点任意点对之间的简单路径的边数之和最大,相同边不重复计算
题解
- 可以确定两个点为树的直径的两端
- 最后一个点为树的直径上的其中一个点往非直径边所能拓展的最深的点
- 两个
bfs
求得树的直径的两个端点,并将直径标记 - 遍历直径上的所有点
dfs
往非直径走,取最大为第三个点
- 两个
C++
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <stack>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <cmath>
using namespace std;
const int N = 3e5 + 50;
int n, m, first[N], nxt[N * 2], to[N * 2], dis[N], len, fa[N];
bool b[N];
void add(int x, int y)
{
nxt[++len] = first[x];
first[x] = len;
to[len] = y;
}
int bfs(int x)
{
queue<int> q;
q.push(x);
memset(dis, 0x7f, sizeof(dis));
memset(fa, 0, sizeof(fa));
dis[x] = 0;
while (!q.empty())
{
int x = q.front();
q.pop();
for (int i = first[x]; i; i = nxt[i])
{
int y = to[i];
if (dis[x] + 1 < dis[y])
{
dis[y] = dis[x] + 1;
q.push(y);
fa[y] = x;
}
}
}
int maxn = 1;
for (int i = 1; i <= n; i++)
if (dis[i] > dis[maxn])
maxn = i;
return maxn;
}
int dfs(int x, int fa)
{
int maxn = 0;
for (int i = first[x]; i; i = nxt[i])
if (to[i] != fa and !b[to[i]])
{
maxn = max(maxn, dfs(to[i], x));
}
return maxn + 1;
}
int dfs(int x, int fa, int len)
{
if (len == 1)
return x;
for (int i = first[x]; i; i = nxt[i])
if (to[i] != fa and !b[to[i]])
{
int y = dfs(to[i], x, len - 1);
if (y)
return y;
}
return 0;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("r.txt", "r", stdin);
#endif
ios::sync_with_stdio(false);
cin >> n;
for (int x, y, i = 1; i < n; i++)
{
cin >> x >> y;
add(x, y);
add(y, x);
}
int y = bfs(1), x = bfs(y), k = x, ans = dis[x];
b[k] = true;
while (fa[k])
{
k = fa[k];
b[k] = true;
}
int z = x;
for (int i = 1; i <= n; i++)
if (b[i])
{
dis[i] = dfs(i, 0);
if (i != x and i != y)
z = i;
}
for (int i = 1; i <= n; i++)
if (b[i] and dis[i] > dis[z])
z = i;
cout << ans + dis[z] - 1 << endl;
cout << x << " " << y << " " << dfs(z, 0, dis[z]);
}