并查集练习题

本文介绍了一种用于模拟疾病如SARS在大学校园内潜在传播情况的算法。通过学生群体间的联系建立模型,确定可能受感染的学生数量上限。该算法利用并查集数据结构来高效处理大量学生之间的关系。

练习1

ZJU1789                                     The Suspects




Severe acute respiratory syndrome (SARS), an atypical pneumonia of unknown aetiology, was recognized as a global threat in mid-March 2003. To minimize transmission to others, the best strategy is to separate the suspects from others.
In the Not-Spreading-Your-Sickness University (NSYSU), there are many student groups. Students in the same group intercommunicate with each other frequently, and a student may join several groups. To prevent the possible transmissions of SARS, the NSYSU collects the member lists of all student groups, and makes the following rule in their standard operation procedure (SOP).
Once a member in a group is a suspect, all members in the group are suspects.
However, they find that it is not easy to identify all the suspects when a student is recognized as a suspect. Your job is to write a program which finds all the suspects.
Input
The input file contains several cases. Each test case begins with two integers n and m in a line, where n is the number of students, and m is the number of groups. You may assume that 0 < n <= 30000 and 0 <= m <= 500. Every student is numbered by a unique integer between 0 and n−1, and initially student 0 is recognized as a suspect in all the cases. This line is followed by m member lists of the groups, one line per group. Each line begins with an integer k by itself representing the number of members in the group. Following the number of members, there are k integers representing the students in this group. All the integers in a line are separated by at least one space.
A case with n = 0 and m = 0 indicates the end of the input, and need not be processed.
Output
For each case, output the number of suspects in one line.
Sample Input
100 4
2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2
1 5
5 1 2 3 4 5
1 0
0 0
Sample Output
4
1
1
#include <iostream>
#include <stdio.h>
#define N 30005

using namespace std;
int father[N];

void init(int n)
{
    int i;
    for(i = 0; i < n; i++)
    {
        father[i] = i;
    }
    return;
}

int getfather(int v)
{

    int geng = v;
    int temp;
    while(geng != father[geng])
    {
        geng = father[geng];
    }
    while(v != geng)
    {
        temp = father[v];
        father[v] = geng;
        v = temp;
    }
    return geng;

}

void Union(const int& i,const int& j)
{
    int x = getfather(i);
    int y = getfather(j);
    if(x == 0)
    {
        father[y] = 0;
    }
    else if(y == 0)
    {
        father[x] = 0;
    }
    else
        father[y] = x;


}
int main()
{
    int n, m;
    int k, a, b;
    while(~scanf("%d%d", &n, &m) && n + m)
    {
        int cot = 0;
        init(n);
        for(int i = 0; i < m; i++)
        {
            cin >> k;
            cin >> a;
            for(int j = 0; j < k - 1; j++)
            {
                cin >> b;
                Union(a, b);
            }
        }
        for(int i = 0; i < n; i++)
        {
            if(getfather(i) == 0)
            {
                cot++;
            }
        }
        cout << cot << endl;
    }
    return 0;
}


练习2

POJ2524                                    Ubiquitous Religions

There are so many different religions in the world today that it is difficult to keep track of them all. You are interested in finding out how many different religions students in your university believe in.

You know that there are n students in your university (0 < n <= 50000). It is infeasible for you to ask every student their religious beliefs. Furthermore, many students are not comfortable expressing their beliefs. One way to avoid these problems is to ask m (0 <= m <= n(n-1)/2) pairs of students and ask them whether they believe in the same religion (e.g. they may know if they both attend the same church). From this data, you may not know what each person believes in, but you can get an idea of the upper bound of how many different religions can be possibly represented on campus. You may assume that each student subscribes to at most one religion.
Input
The input consists of a number of cases. Each case starts with a line specifying the integers n and m. The next m lines each consists of two integers i and j, specifying that students i and j believe in the same religion. The students are numbered 1 to n. The end of input is specified by a line in which n = m = 0.
Output
For each test case, print on a single line the case number (starting with 1) followed by the maximum number of different religions that the students in the university believe in.
Sample Input
10 9
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
10 4
2 3
4 5
4 8
5 8
0 0
Sample Output
Case 1: 1
Case 2: 7
Hint
Huge input, scanf is recommended.
                          


#include <iostream>
#include <stdio.h>
#define N 50005

using namespace std;
int father[N];
int num[N];
int cot;
static int cas = 0;

void init(int n)
{
    int i;
    for(i = 1; i <= n; i++)
    {
        father[i] = i;
        num[i] = 1;
    }
    return;
}

int getfather(int v)
{
    int geng = v;
    int temp;
    while(geng != father[geng])
    {
        geng = father[geng];
    }
    while(v != geng)
    {
        temp = father[v];
        father[v] = geng;
        v = temp;
    }
    return geng;
}

void Union(int a, int b)
{
    int x = getfather(a);
    int y = getfather(b);
    if(x == y)
    {
        return;
    }
    else
    {
        cot -= 1;
        if(num[x] > num[y])
        {
            father[y] = x;
            num[x] += num[y];
        }
        else
        {
            father[x] = y;
            num[y] += num[x];
        }

    }
}

bool judge(int a, int b)
{
    if(getfather(a) == getfather(b))
        return true;
    else
        return false;

}

int main()
{
    int n;
    long long m;
    int a, b;
    while(~scanf("%d%I64d", &n, &m) && (n + m))
    {
        init(n);
        cot = n;
        for(int i = 1; i <= m; i++)
        {
            scanf("%d%d", &a, &b);
            Union(a, b);
        }
        printf("Case %d: %d\n", ++cas, cot);
    }
}


### 关于可撤销并查集的洛谷练习题及相关数据结构 #### 可撤销并查集简介 可撤销并查集是一种扩展版本的并查集,能够在执行合并操作的同时保留回退的能力。这意味着可以在任意时刻撤消最近的一次 `union` 操作,从而恢复到之前的状态。这一特性使得该数据结构非常适合解决涉及动态连通性和历史状态查询的问题。 实现可撤销并查集的核心在于记录每次路径压缩或合并操作的变化,并将其存入栈中以便后续回溯。具体来说,在标准并查集中引入额外的数据结构(如栈)来保存父节点指针的历史修改情况[^1]。 下面是一些适合初学者和中级选手练习的洛谷平台上的题目: --- #### 推荐洛谷练习题 1. **P2860 [USACO06FEB]Redundant Paths G** 这道题考察的是如何利用带权并查集或者可撤销并查集计算最小边数使图成为双联通分量。虽然不强制要求使用可撤销并查集,但如果尝试用此方法解题会更加直观。 题目链接: https://www.luogu.com.cn/problem/P2860 2. **P3970 [TJOI2015]线性代数** 虽然名字看起来与矩阵运算有关,但实际上可以通过构建虚拟点的方式转化为经典的并查集问题。进一步优化时可以考虑加入可撤销机制以应对复杂度较高的测试样例。 题目链接: https://www.luogu.com.cn/problem/P3970 3. **P4180 [BJOI2012]树的难题** 此题需要维护森林中的多个独立子树之间的连接关系,并支持删除某些边的操作。因此非常适合作为学习可撤销并查集的应用实例之一。 题目链接: https://www.luogu.com.cn/problem/P4180 4. **P2024 [AHOI2009]中国象棋** 将二维网格抽象成一维数组之后,可以用带有时间戳功能的可撤销并查集高效解答本题提出的询问类问题。 题目链接: https://www.luogu.com.cn/problem/P2024 --- #### 实现代码示例 以下是一个简单的 C++ 版本的可撤销并查集模板程序: ```cpp #include <bits/stdc++.h> using namespace std; struct UndoUnionFind { vector<int> parent; vector<pair<int, int>> history; // 记录每一次改变 (x, old_parent) UndoUnionFind(int n): parent(n){ for(int i=0;i<n;i++) parent[i]=i; } int find_set(int x) { while(parent[x]!=x){ history.emplace_back(x,parent[x]); parent[x]=parent[parent[x]]; // Path compression x=parent[x]; } return x; } bool unite_sets(int x, int y){ int fx=find_set(x); int fy=find_set(y); if(fx !=fy ){ history.emplace_back(fy,fy); // Record the change of root node's father. parent[fy]=fx; return true; } return false; } void undo(){ if(history.empty())return ; auto &[node,new_father]=history.back(); parent[node]=new_father; history.pop_back(); } }; int main() { int n,m,q; cin >> n >> m >> q; UndoUnionFind uf(n+1); for(int i=0;i<m;i++){ int u,v; cin>>u>>v; uf.unite_sets(u,v); } while(q--){ string cmd; cin>>cmd; if(cmd=="undo"){ uf.undo(); }else{ int u,v; cin>>u>>v; cout <<(uf.find_set(u)==uf.find_set(v)? "YES":"NO")<<'\n'; } } } ``` --- #### 总结 通过以上介绍可以看出,掌握好基础版并查集的基础上再去深入理解其变种形式——比如种类并查集以及今天的主题可撤销并查集——对于提高算法竞赛水平至关重要。这些技巧不仅限于比赛场景下有用,在实际软件开发过程中也可能遇到类似的逻辑需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值