【PAT甲级 - C++题解】1021 Deepest Root

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1021 Deepest Root (pintia.cn)
🔑中文翻译:最深的根
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

1021 Deepest Root

A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤104) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N−1 lines follow, each describes an edge by given the two adjacent nodes’ numbers.

Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print Error: K components where K is the number of connected components in the graph.

Sample Input 1:

5
1 2
1 3
1 4
2 5

Sample Output 1:

3
4
5

Sample Input 2:

5
1 3
1 4
2 5
3 4

Sample Output 2:

Error: 2 components
题意

第一行包含整数 N N N ,表示节点数量。

节点编号为 1 ∼ N 1∼N 1N

接下来 N − 1 N−1 N1 行,每行包含两个整数,表示两个节点之间存在一条边。

输出最深的根的节点编号。

如果最深的根不唯一,则按照从小到大的顺序,将它们依次输出,每个占一行。

如果给定的图不是树,输出 Error: K components ,其中 K K K 是图中连通分量的数量。

思路
  1. 在输入每条边的信息时,我们可以利用并查集来对该图进行判断,输入前令 k = n ,每输入一条边时就判断这条边两个端点是否已经在同一个连通块中,如果不在则将 k - 1 ,最终的 k 值就是该图连通块的数量。
  2. 如果 k > 1 则该图不是树,输出 Error: K components ,否则对每个结点都进行一次 dfs 操作,找到最深的结点。注意,我们这里的结点是从小到大进行 dfs ,所以最终得到的结果一定是单调递增的,不用再进行排序。
  3. dfs 的过程中,注意不能回溯即当前结点再访问其父结点,需要额外进行判断。
代码
#include<bits/stdc++.h>
using namespace std;

const int N = 10010, M = 2 * N;
int h[N], e[M], ne[M], idx;
int p[N];
int n;

//链式前向星保存每一条边
void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

//并查集查找操作
int find(int x)
{
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

//获取当前最大深度,其中u表示当前结点,father表示父结点
int dfs(int u, int father)
{
    int depth = 0;
    //遍历其所有孩子结点
    for (int i = h[u]; ~i; i = ne[i])
    {
        int j = e[i];
        if (j == father)   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++)   p[i] = i;

    //输入所有边,且用并查集判断该图是否为树
    int k = n;
    for (int i = 0; i < n - 1; i++)
    {
        int a, b;
        cin >> a >> b;
        add(a, b), add(b, a);
        if (find(a) != find(b))
        {
            k--;
            p[find(a)] = find(b);
        }
    }

    if (k > 1) printf("Error: %d components\n", k);
    else
    {
        vector<int> nodes;
        int max_depth = 0;
        for (int i = 1; i <= n; i++)
        {
            int depth = dfs(i, 0); //获得当前深度
            if (depth > max_depth) //如果当前深度大于当前最大深度
            {
                nodes.clear();
                max_depth = depth;
                nodes.push_back(i);
            }
            else if (depth == max_depth)   //如果当前深度等于当前最大深度
                nodes.push_back(i);
        }

        //输出结果
        for (auto& x : nodes)  cout << x << endl;
    }

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]:这段代码是一个解决LeetCode上某个题目的C++实现,具体是一个双指针的解法。该题目是计算一个数组中的积水量。代码中使用了两个指针分别指向数组的左右边界,然后通过比较左右指针所指向的元素的大小,来确定当前位置的积水量。具体的计算方法是,如果左指针所指向的元素小于右指针所指向的元素,则对左指针的左边进行操作,如果左指针所指向的元素大于等于右指针所指向的元素,则对右指针的右边进行操作。在每一次操作中,都会更新左边的最大值和右边的最大值,并计算当前位置的积水量。最后返回总的积水量。\[1\] 引用\[2\]:这段代码是另一个解决LeetCode上某个题目的C++实现,具体是一个深度优先搜索的解法。该题目是计算一个二维网格中从起点到终点的可行路径数量。代码中使用了递归的方式进行深度优先搜索,从起点开始,每次向下或向右移动一步,直到到达终点。在每一步移动中,会判断当前位置是否有障碍物,如果有障碍物则返回0,如果到达终点则返回1,否则继续递归搜索下一步的位置。最后返回总的可行路径数量。\[2\] 引用\[3\]:这段代码是另一个解决LeetCode上某个题目的C++实现,具体是一个动态规划的解法。该题目是计算一个数组中的积水量。代码中使用了动态规划的思想,通过遍历数组中的每个元素,分别计算该元素左边和右边的最大值,并计算当前位置的积水量。最后返回总的积水量。\[3\] 综上所述,这三段代码分别是解决LeetCode上不同题目的C++实现,分别使用了双指针、深度优先搜索和动态规划的方法来解决问题。 #### 引用[.reference_title] - *1* *3* [Leetcode 热题100 42.接雨水(C++ 多种解法,错过可惜)](https://blog.csdn.net/qq_51933234/article/details/124637883)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [[C++]Leetcode 不同路径 || 解题思路及详解](https://blog.csdn.net/weixin_62712365/article/details/123951736)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值