1021 Deepest Root (PAT甲级)

这篇具有很好参考价值的文章主要介绍了1021 Deepest Root (PAT甲级)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1021. Deepest Root (25)-PAT甲级真题(图的遍历,dfs,连通分量的个数)_柳婼的博客-CSDN博客

柳婼的解法在这里,两次dfs,还是挺好玩的。

我的解法比较暴力,就是先用并查集算连通分量(这个其实还是dfs来算会更方便),如果只有一个连通分量,那deepest root一定在仅有一条arc的点上(除了只有一个结点的树,可以一开始就特殊考虑),然后从这些点开始dfs,算出深度最高的那些root。

#include <cstdio>
#include <vector>
#include <algorithm>
#include <set>
const int maxN = 10001;

int N, u, v, maxx, layer, maxL;
int fa[maxN];
std::set<int> st, root;
std::vector<std::vector<int>> adj;
std::vector<bool> visited;

int findFather(int m){
    int a = m;
    while(fa[a] != a){
        a = fa[a];
    }
    int t;
    while(fa[m] != m){
        t = fa[m];
        fa[m] = a;
        m = t;
    }
    return a;
}

void myUnion(int m, int n){
    fa[findFather(m)] = findFather(n);
}

void dfs(int k){
    visited[k] = true;
    ++layer;
    if(layer > maxL){
        maxL = layer;
    }
    for(int i = 0; i < adj[k].size(); ++i){
        if(!visited[adj[k][i]]){
            dfs(adj[k][i]);
        }
    }
    --layer;
}

int main(){
    scanf("%d", &N);
    if(N == 1){
        printf("1");
        return 0;
    }
    adj.resize(N + 1);
    visited.resize(N + 1);
    for(int i = 1; i <= N; ++i){
        fa[i] = i;
    }
    for(int i = 1; i < N; ++i){
        scanf("%d %d", &u, &v);
        adj[u].push_back(v);
        adj[v].push_back(u);
        myUnion(u, v);
    }
    for(int i = 1; i <= N; ++i){
        st.insert(findFather(i));
    }
    if(st.size() != 1){
        printf("Error: %d components", st.size());
        return 0;
    }
    maxx = 0;
    for(int i = 1; i <= N; ++i){
        if(adj[i].size() == 1){
            maxL = 0;
            layer = 0;
            std::fill(visited.begin() + 1, visited.end(), false);
            dfs(i);
            if(maxL > maxx){
                maxx = maxL;
                root.clear();
                root.insert(i);
            } else if(maxL == maxx){
                root.insert(i);
            }
        }
    }
    for(auto c : root){
        printf("%d\n", c);
    }
    return 0;
}

题目如下:

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 componentswhere K is the number of connected components in the graph.文章来源地址https://www.toymoban.com/news/detail-614186.html

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

到了这里,关于1021 Deepest Root (PAT甲级)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 图论算法|深度优先搜索理论基础|797.所有可能的路径|广度优先搜索BFS理论基础|200. 岛屿数量

    dfs是可一个方向去搜,不到黄河不回头,直到遇到绝境了,搜不下去了,在换方向(换方向的过程就涉及到了回溯)。 递归和回溯是相辅相成的 https://leetcode.cn/problems/all-paths-from-source-to-target/ 有向无环图(DAG): 有环无向图是指在图中存在至少一个环(Cycle)的无向图。环是

    2024年02月15日
    浏览(60)
  • 【算法导论】图论(图的基本概念,图上的深度优先搜索(DFS),广度优先搜索(BFS),最小生成树(MST)及Prim,Kruskal算法)

    图(Graph)是一种包含节点与节点的边的集合,记作G=(V,E),V是节点的集合,E是边的集合。 有向图 一个有向图G=(V,E),E中每个元素是V上的一个二值关系:一条从a出发的连向b的边e可以记作一个 有序 对e = (a,b) 。 无向图 一个无向图G=(V,E),E的每个元素e可以表示V上的一个 无序 对,记

    2024年02月03日
    浏览(52)
  • PAT 甲级【1010 Radix】

    本题范围long型(35)^10 枚举radix范围上限pow(n/a0,1/m)上,考虑上限加1.范围较大。使用二分查找枚举 代码如下 本页面将简要介绍二分查找,由二分法衍生的三分法以及二分答案。 二分查找(英语:binary search),也称折半搜索(英语:half-interval search)、对数搜索(英语:logar

    2024年02月08日
    浏览(39)
  • PAT 甲级考试【1003 Emergency】

    题目: As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the length of each road between any pair of cities are marked on the map. When there is an emergency call to you from some other city, your job is to lead

    2024年02月08日
    浏览(49)
  • 菜鸟记录PAT甲级1003--Emergency

    久违的PAT,由于考研408数据结构中有一定需要,同时也是对先前所遗留的竞赛遗憾进行一定弥补 ,再次继续PAT甲级1003.。 As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the l

    2023年04月13日
    浏览(45)
  • 1114 Family Property (PAT甲级)

    This time, you are supposed to help us collect the data for family-owned property. Given each person\\\'s family members, and the estate(房产)info under his/her own name, we need to know the size of each family, and the average area and number of sets of their real estate. Input Specification: Each input file contains one test case. For each case, the fir

    2024年02月06日
    浏览(51)
  • 1028 List Sorting (PAT甲级)

    Excel can sort records according to any column. Now you are supposed to imitate this function. Input Specification: Each input file contains one test case. For each case, the first line contains two integers N (≤105) and C, where N is the number of records and C is the column that you are supposed to sort the records with. Then N lines follow, eac

    2024年02月15日
    浏览(41)
  • 1072 Gas Station (PAT甲级)

    A gas station has to be built at such a location that the minimum distance between the station and any of the residential housing is as far away as possible. However it must guarantee that all the houses are in its service range. Now given the map of the city and several candidate locations for the gas station, you are supposed to give the best recommendatio

    2024年02月09日
    浏览(42)
  • 1111 Online Map (PAT甲级)

    这道题我读题不仔细导致踩了个大坑,一个测试点过不了卡了好几个小时:第二个dijkstra算法中,题目要求是“In case the fastest path is not unique, output the one that passes through the fewest intersections”,我却想当然地认为在fastest path is not unique的时候,判断标准是最短距离…… Input our

    2024年02月07日
    浏览(43)
  • pat甲级 1022 Digital Library

    A Digital Library contains millions of books, stored according to their titles, authors, key words of their abstracts, publishers, and published years. Each book is assigned an unique 7-digit number as its ID. Given any query from a reader, you are supposed to output the resulting books, sorted in increasing order of their ID\\\'s. Input Specification: Each inp

    2024年04月15日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包