1021. Deepest Root (25) 并查集&&DFS

本博客探讨了如何在给定的图结构中找到深度最大的根节点,即所谓的最深根节点。通过实现深度优先搜索算法并利用邻接表进行图的存储,我们能够有效地解决这个问题。同时,博客还提供了输入输出示例,帮助读者理解算法的运行流程及应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1021. Deepest Root (25)
时间限制
1500 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 (<=10000) 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

提交代码


这道题要注意一点要用邻接表存储图,如果用邻接矩阵会超时(稀疏图)

第一次写有返回值的DFS,还不是很熟练

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=10001;
bool vis[maxn];
int a[maxn];
int n;
int cnt=0;
vector<int> ma[maxn];//邻接表
int d[maxn];//计算以这个点为树根时的最大深度
int dfs(int s)//dfs表示以S为起点所能达到的最大深度
{
    int ans=0;
    if(vis[s])return 0;//这个点已经被访问过,明显以这个点的最大深度是0
    vis[s]=true;
    int m=ma[s].size();
    for(int i=0; i<m; i++)
    {
        if(!vis[ma[s][i]])
        {
            int tmp=dfs(ma[s][i]);//以当前点为起点访问能到达的最大的深度,也就是找出S的邻接点里的,深度,能达到的最大的
            ans=max(ans,tmp);//ans记录下最大的深度即可
        }
    }
    return ans+1;//能到这里说明以S点能到达的深度可以加一,也就是S相邻的顶点里的深度,最大值,加上S点,所以就是ans+1
}

void init(int n)//这是并查集的初始化
{
    for(int i=0; i<=n; i++)
        a[i]=i;
}
int find(int x)//并查集查找X的父亲,带路径压缩
{
    if(a[x]!=x)
        a[x]=find(a[x]);
    return a[x];
}
void unio(int x,int y)//合并X,Y到一起
{
    x=find(x);
    y=find(y);
    if(a[x]==a[y])return ;
    a[x]=y;
}

int main()
{
    int i,j,k,t;
    // freopen("in.txt","r",stdin);
    cin>>n;
    init(n);
    for(i=1; i<n; i++)
    {
        int s,e;
        cin>>s>>e;
        unio(s,e);
        ma[s].push_back(e);
        ma[e].push_back(s);
    }

    int sum=0;//判断连通分量的个数
    for(i=1; i<=n; i++)
    {
        if(a[i]==i)sum++;
    }
    if(sum>1)
    {
        printf("Error: %d components\n",sum);
        return 0;
    }
    else
        for(i=1; i<=n; i++)
            {
                memset(vis,0,sizeof(vis));
                d[i]=dfs(i);
            }
    int maxv=-1;int index=0;
    for(i=1;i<=n;i++)if(d[i]>maxv){maxv=d[i];index=i;}
    for(j=1;j<=n;j++)if(d[j]==d[index])
        printf("%d\n",j);


}





### 使用 `mkdir` 创建目录并结合 `cd` 切换到该目录 在 Linux 或 Shell 环境下,可以利用 `mkdir` 命令创建新的目录,并通过 `cd` 命令切换至所创建的目录。 #### 1. 创建单个目录 要创建一个单独的新目录,可以直接使用 `mkdir` 后跟目标名称。例如: ```bash mkdir example_directory ``` 这将在当前工作目录下创建名为 `example_directory` 的新目录[^1]。 #### 2. 创建嵌套多级目录 当需要一次性创建多个层次结构的目录时,可附加 `-p` 参数给 `mkdir` 命令。这样即使父目录不存在也会被自动创建。例如: ```bash mkdir -p parent/child/grandchild ``` 上述命令不仅会创建最终子目录 `grandchild`, 还会在必要时依次构建其上级目录 `parent` 和 `child`[^3]。 #### 3. 切换到新建目录 一旦成功创建了所需的目录之后,就可以运用 `cd` (Change Directory) 来改变当前位置到达刚刚建立的那个地方。比如先执行上面提到过的单一目录创建动作后再输入如下语句即可进入其中: ```bash cd example_directory ``` 或者对于多层次的情况,则应指定完整的相对或绝对路径来进行转换: ```bash cd parent/child/grandchild ``` 值得注意的是,如果尝试切换的目标并非真实存在的话,那么将会收到错误提示告知无法找到这样的文件夹位置[^4]。 #### 完整流程演示 以下是将以上步骤结合起来的一个简单实例脚本展示整个过程从无到有地建立起一套复杂的存储架构然后再访问它们的过程。 ```bash #!/bin/bash # Step A: Create complex nested directories structure. mkdir -p /tmp/example/multi/level/directory # Step B: Change into the deepest created subdirectory. cd /tmp/example/multi/level/directory || exit # Optional C: Verify current location after changing. pwd ``` 此段代码首先定义了一个较为深入的树形数据集模型并通过一步到位的方式完成了全部节点初始化作业;接着马上定位到了最末端叶子结点处准备开展后续具体业务逻辑运算活动之前确认一下确切地址信息以便调试排查之需[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值