并查集进阶———小希的迷宫,is it a tree

本文探讨了如何通过编程判断给定的迷宫设计或节点集合是否构成一棵树。使用并查集算法验证是否存在唯一路径连接任意两点,避免回路和自环,确保树结构的有效性。

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

B - 小希的迷宫

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

上次Gardon的迷宫城堡小希玩了很久(见Problem B),现在她也想设计一个迷宫让Gardon来走。但是她设计迷宫的思路不一样,首先她认为所有的通道都应该是双向连通的,就是说如果有一个通道连通了房间A和B,那么既可以通过它从房间A走到房间B,也可以通过它从房间B走到房间A,为了提高难度,小希希望任意两个房间有且仅有一条路径可以相通(除非走了回头路)。小希现在把她的设计图给你,让你帮忙判断她的设计图是否符合她的设计思路。比如下面的例子,前两个是符合条件的,但是最后一个却有两种方法从5到达8。

 

Input

输入包含多组数据,每组数据是一个以0 0结尾的整数对列表,表示了一条通道连接的两个房间的编号。房间的编号至少为1,且不超过100000。每两组数据之间有一个空行。
整个文件以两个-1结尾。

 

Output

对于输入的每一组数据,输出仅包括一行。如果该迷宫符合小希的思路,那么输出"Yes",否则输出"No"。

 

Sample Input

6 8 5 3 5 2 6 4 5 6 0 0 8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0 3 8 6 8 6 4 5 3 5 6 5 2 0 0 -1 -1

 

Sample Output

Yes Yes No

思路:要找符合条件的,则要判断是否构成回路,并且判断有且仅有一棵树。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
int flag;
int bin[100005];
int vis[100005]; //标记数组

int findx(int x) //找祖先
{
    int r=x;
    while(bin[r]!=r)
    {
        r=bin[r];
    }
    return r;
}
void unionxy(int x,int y) //连接两个点
{
    int fx,fy;
    fx=findx(x);
    fy=findx(y);
    if(fx!=fy)
    {
        bin[fx]=fy;
    }
    else //构成了回路,不是一棵树
    {
        flag=0;
    }
}


int main()
{
    int i,a,b;
    while(~scanf("%d %d",&a,&b))
    {
        if(a==-1&&b==-1)
            break;
        if(a==0&&b==0)
        {
            cout<<"Yes"<<endl;
            continue;
        }
        for(i=0; i<100005; i++)
        {
            bin[i]=i;
            vis[i]=0; //把每个点先初始化为零
        }
        unionxy(a,b);
        flag=1;
        vis[a]=1; //把出现过的点标记
        vis[b]=1;
        while(scanf("%d %d",&a,&b)&&a&&b)
        {
            unionxy(a,b);
            vis[a]=1;  //把出现过的点标记
            vis[b]=1;
        }
        if(flag==0)
        {
            cout<<"No"<<endl;
            continue;
        }
        else
        {
            int sum=0;
            for(i=0; i<100005; i++)
            {
                if(vis[i]==1&&bin[i]==i) //这个点出现过并且祖先是他自己则它是祖先
                    sum++;
            }
            if(sum==1) //一棵数只能有一个祖先,如果出现大于1则不止一个祖先即不止一棵树
                cout<<"Yes"<<endl;
            else
                cout<<"No"<<endl;
        }
    }
}

 

 

 

D - Is It A Tree?

Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

Description

A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties.

There is exactly one node, called the root, to which no directed edges point.
Every node except the root has exactly one edge pointing to it.
There is a unique sequence of directed edges from the root to each node.
For example, consider the illustrations below, in which nodes are represented by circles and edges are represented by lines with arrowheads. The first two of these are trees, but the last is not.


In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.

Input

The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero.

Output

For each test case display the line "Case k is a tree." or the line "Case k is not a tree.", where k corresponds to the test case number (they are sequentially numbered starting with 1).

Sample Input

6 8  5 3  5 2  6 4
5 6  0 0

8 1  7 3  6 2  8 9  7 5
7 4  7 8  7 6  0 0

3 8  6 8  6 4
5 3  5 6  5 2  0 0
-1 -1

Sample Output

Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.

思路:判断是否是一棵树。和上一道题几乎是一样的,不过要注意的是,存在自环不是一棵树。上一道题自环输出的是yes。

不是一棵树的条件:自环,形成回路,森林。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
int flag;
int bin[100005];
int vis[100005];
int findx(int x)
{
    int r=x;
    while(bin[r]!=r)
    {
        r=bin[r];
    }
    return r;
}
void unionxy(int x,int y)
{
    if(x==y) //如果形成自环也不行
        flag=0;
    int fx,fy;
    fx=findx(x);
    fy=findx(y);
    if(fx!=fy)
    {
        bin[fx]=fy;
    }
    else
    {
        flag=0;
    }
}

int main()
{
    int i,a,b;
    int t=1;
    while(~scanf("%d %d",&a,&b))
    {
        if(a==-1&&b==-1)
            break;
        if(a==0&&b==0)
        {
            printf("Case %d is a tree.\n",t++);
            continue;
        }
        for(i=0; i<100005; i++)
        {
            bin[i]=i;
            vis[i]=0;
        }
        unionxy(a,b);
        flag=1;
        if(a==b)  //判断自环的情况
        {
            flag=0;
        }
        vis[a]=1;
        vis[b]=1;
        while(scanf("%d %d",&a,&b)&&a&&b)
        {
            unionxy(a,b);
            vis[a]=1;
            vis[b]=1;
        }
        if(flag==0)
        {
            printf("Case %d is not a tree.\n",t++);
            continue;
        }
        else
        {
            int sum=0;
            for(i=0; i<100005; i++)
            {
                if(vis[i]==1&&bin[i]==i)
                    sum++;
            }
            if(sum==1)
                printf("Case %d is a tree.\n",t++);
            else
                printf("Case %d is not a tree.\n",t++);
        }
    }
}

 

### C语言并查集实现迷宫问题算法 #### 背景介绍 迷宫问题是经典的图论问题之一,通常可以通过深度优先搜索 (DFS) 或广度优先搜索 (BFS) 来解决。然而,并查集(Union-Find)也可以用于处理某些类型的迷宫问题,特别是涉及动态连通性的场景。 并查集是一种高效的数据结构,主要用于管理一组不相交集合的合并与查询操作。它非常适合用来判断两个节点是否属于同一个连通分量,在迷宫中可以表示为判断两点之间是否存在路径[^2]。 --- #### 并查集的核心概念 1. **Find**: 查找某个元素所属的集合根节点。 2. **Union**: 合并两个不同集合。 3. **Path Compression**: 在执行 `Find` 操作时优化树的高度,使得后续查找更快。 4. **Rank Optimization**: 使用秩来控制树的高度,进一步提升效率。 这些特性使并查集成为一种高效的工具,尤其适用于需要频繁更新和查询连通关系的情况。 --- #### C语言实现思路 以下是基于并查集解决迷宫问题的一个通用框架: 1. 将迷宫抽象成一个二维网格,其中每个单元格代表一个顶点。 2. 如果相邻的两个单元格之间有通道,则认为这两个顶点相连。 3. 利用并查集维护所有顶点之间的连通性。 4. 查询任意两点是否连通即可验证它们是否有路径可达。 --- #### 示例代码 以下是一个完整的 C 语言程序,展示如何利用并查集解决迷宫问题: ```c #include <stdio.h> #define MAX_SIZE 100 // 假设迷宫最大尺寸为 100x100 // 定义方向数组,方便访问上下左右四个邻居 int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; // 迷宫大小 int rows, cols; // 并查集父节点数组 int parent[MAX_SIZE * MAX_SIZE]; // 初始化函数 void init(int n) { for (int i = 0; i < n; ++i) { parent[i] = i; } } // 寻找根节点,带路径压缩 int find_set(int x) { if (parent[x] != x) { parent[x] = find_set(parent[x]); // 路径压缩 } return parent[x]; } // 合并两个集合 void union_set(int x, int y) { int rootX = find_set(x); int rootY = find_set(y); if (rootX != rootY) { parent[rootX] = rootY; } } // 获取一维索引 int get_index(int r, int c) { return r * cols + c; } // 主函数逻辑 int main() { scanf("%d %d", &rows, &cols); // 输入迷宫行列数 // 初始化并查集 init(rows * cols); char maze[rows][cols]; // 存储迷宫状态 for (int i = 0; i < rows; ++i) { getchar(); // 清除换行符 for (int j = 0; j < cols; ++j) { scanf("%c", &maze[i][j]); } } // 遍历迷宫,连接可通行的邻接点 for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (maze[i][j] == '.') { // '.' 表示可通过 for (int k = 0; k < 4; ++k) { int ni = i + dx[k], nj = j + dy[k]; if (ni >= 0 && ni < rows && nj >= 0 && nj < cols && maze[ni][nj] == '.') { int idx1 = get_index(i, j), idx2 = get_index(ni, nj); union_set(idx1, idx2); } } } } } // 测试两点是否连通 int start_r, start_c, end_r, end_c; printf("请输入起点坐标(r,c): "); scanf("%d %d", &start_r, &start_c); printf("请输入终点坐标(r,c): "); scanf("%d %d", &end_r, &end_c); int s_idx = get_index(start_r, start_c); int e_idx = get_index(end_r, end_c); if (find_set(s_idx) == find_set(e_idx)) { printf("存在一条路径可以从起点到终点。\n"); } else { printf("不存在路径从起点到达终点。\n"); } return 0; } ``` --- #### 关键点解析 1. **初始化**:通过 `init` 函数设置每个节点的父亲为自己。 2. **路径压缩**:在 `find_set` 中实现了路径压缩技术,显著提高性能。 3. **迷宫建模**:将二维矩阵转化为一维数组以便于存储和计算。 4. **输入输出设计**:支持灵活输入迷宫布局以及测试起始点和目标点间的连通性。 --- #### 性能分析 该方法的时间复杂度主要取决于并查集的操作次数。由于采用了路径压缩和按秩合并策略,单次 `Find` 和 `Union` 的时间复杂度接近 O(α(N)),其中 α 是阿克曼反函数,增长极其缓慢,实际运行速度非常快。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值