【PAT甲级】1021 Deepest Root(并查集求图的联通分量+dfs求最大深度)

遍历图中的每个节点,每次都将当前节点作为根节点求当前最大深度。

#include <bits/stdc++.h>

using namespace std;

const int N = 10010, M = 2 * N;
int n;
int e[M], ne[M], h[N], idx;
int f[N];
int maxDepth = -1;

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

int find(int x)
{
    if(f[x] != x) f[x] = find(f[x]);
    return f[x];
}

int dfs(int u, int father)
{
    int depth = 0;
    for(int i = h[u]; ~i; i = ne[i])
    {
        int j = e[i];
        if(father == j) continue;
        depth = max(depth, dfs(j, u) + 1);
    }

    return depth;
}

int main()
{
    cin >> n;
    memset(h, -1, sizeof h);
    for(int i = 1; i <= n; i++) f[i] = i;
    
    int k = n;
    for(int i = 0; i < n; i++)
    {
        int a, b;
        cin >> a >> b;
        add(a, b); add(b, a);
        if(find(a) != find(b))
        {
            k --;
            f[find(b)] = find(a);
        }
    }

    if(k != 1) printf("Error: %d components", k);
    else
    {
        vector<int> nodes;
        for(int i = 1; i <= n; i++)
        {
            int depth = dfs(i, -1);
            if(depth > maxDepth)
            {
                nodes.clear();
                nodes.push_back(i);
                maxDepth = depth;
            }
            else if(depth == maxDepth) nodes.push_back(i);
        }

        for(auto n : nodes) cout << n << endl;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值