[CF1294F] Three Paths on a Tree - 树的直径
Description
给定一棵含 \(n\ (3\leq n\leq2\cdot 10^5)\) 个结点的无权树,试找出三个结点 \(u\)、\(v\)、\(w\),\(\operatorname{s.t.}\) $$\operatorname{card}({u,v\text{ 间的路径}}\cup{v,w\text{ 间的路径}}\cup{w,u\text{ 间的路径}})$$ 最大。输出方案。
Solution
直径以及距离直径的最远点(反证法)
两次 DFS + BFS
#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
int n;
vector<int> g[N];
int d[N], v[N];
void dfs(int p, int from)
{
for (int q : g[p])
if (q != from)
{
d[q] = d[p] + 1;
dfs(q, p);
}
}
vector<int> path;
bool find_path(int p, int from, int tar)
{
path.push_back(p);
if (tar == p)
return true;
for (int q : g[p])
if (q != from)
{
if (find_path(q, p, tar))
return true;
}
path.pop_back();
return false;
}
signed main()
{
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i < n; i++)
{
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs(1, 0);
int p = 0;
for (int i = 1; i <= n; i++)
if (d[i] > d[p])
p = i;
d[p] = 0;
dfs(p, 0);
int q = 0;
for (int i = 1; i <= n; i++)
if (d[i] > d[q])
q = i;
int len1 = d[q];
find_path(p, 0, q);
queue<int> que;
for (int i = 1; i <= n; i++)
d[q] = n + 1;
for (int i : path)
que.push(i), d[i] = 0, v[i] = 1;
int last = 0;
while (que.size())
{
int now = que.front();
que.pop();
if (now != p && now != q)
last = now;
for (int q : g[now])
{
if (d[q] > d[now] + 1)
{
d[q] = d[now] + 1;
if (!v[q])
v[q] = 1, que.push(q);
}
}
}
int len2 = d[last];
cout << len1 + len2 << endl;
cout << p << " " << q << " " << last << endl;
}