codeforces 1294F Three Paths on a Tree

传送门

题意

给你一棵树,任取三个点,使得这三个点任意点对之间的简单路径的边数之和最大,相同边不重复计算

题解

  • 可以确定两个点为树的直径的两端
  • 最后一个点为树的直径上的其中一个点往非直径边所能拓展的最深的点
    • 两个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]);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值