Codeforces 1294F three paths on a tree

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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值