Codeforces 1294F three paths on a tree
题解:
树的直径的思想,但是这里是三个点,并非两个点,但是我们任然可以用树的直径的思想,首先肯定存在x,y两个端点他们之间的距离是图中任意两点间最远的。其次我们第三个点肯定是和x,y的距离和加起来在任意三点间距离和最大。
然后我们定义
p
=
l
c
a
(
x
,
y
,
c
)
p=lca(x,y,c)
p=lca(x,y,c)可以知道:
d
e
p
t
h
(
a
,
b
)
=
d
e
p
t
h
(
a
,
p
)
+
d
e
p
t
h
(
b
,
p
)
depth(a,b)=depth(a,p)+depth(b,p)
depth(a,b)=depth(a,p)+depth(b,p)
d
e
p
t
h
(
a
,
c
)
=
d
e
p
t
h
(
a
,
p
)
+
d
e
p
t
h
(
c
,
p
)
depth(a,c)=depth(a,p)+depth(c,p)
depth(a,c)=depth(a,p)+depth(c,p)
d
e
p
t
h
(
c
,
b
)
=
d
e
p
t
h
(
c
,
p
)
+
d
e
p
t
h
(
b
,
p
)
depth(c,b)=depth(c,p)+depth(b,p)
depth(c,b)=depth(c,p)+depth(b,p)
所以我们求和出来的答案需要除以2。
d
i
s
(
x
)
dis(x)
dis(x)代表源点到x的距离,第一次以1为源点我们找最远的x,然后以x为源点找最远的y,至此我们就找到了一条直径,然后再以y为源点找到最远的c,再更新距离。
#include <bits/stdc++.h>
//#define int long long
using namespace std;
const int N=2e5+7;
int cnt,ne[N<<1],e[N<<1],head[N];
int dis[N],sum[N];
void add(int a,int b)
{
e[cnt]=b,ne[cnt]=head[a],head[a]=cnt++;
}
int bfs(int x)
{
queue<int> q;
memset(dis,0,sizeof dis);
q.push(x);
int u;
while(!q.empty()){
u=q.front(); q.pop();
for(int i=head[u];~i;i=ne[i]){
int j=e[i];
if(j!=x&&!dis[j]){
q.push(j);
dis[j]=dis[u]+1;
}
}
}
return u;
}
int main()
{
memset(head,-1,sizeof head);
int n; cin>>n;
for(int i=1;i<n;i++){
int a,b; scanf("%d%d",&a,&b);
add(a,b);
add(b,a);
}
int x=bfs(1),y=bfs(x);
for(int i=1;i<=n;i++) sum[i]+=dis[i]+dis[y];
bfs(y);
int res=0,ans;
for(int i=1;i<=n;i++){
sum[i]+=dis[i];
if(i!=x&&i!=y&&sum[i]>res) res=sum[i],ans=i;
}
printf("%d\n%d %d %d\n",res/2,x,y,ans);
}