并查集练习(0743) SWUST OJ

本文详细介绍了并查集算法的基本概念,并通过一个具体的编程实例展示了如何使用C++实现并查集,包括查找根节点和混合操作等功能,最后通过实际问题验证了算法的有效性。

#include<iostream>
#include<cstring>
using namespace std;
int a[1000005];
int n,m,l,ci,di;

int root(int x)        //找到根节点 
{
    int r = x;
    while(r != a[r])
        r = a[r];
    int i = x,j;
    while(i != r)    //压缩路径 
    {
        j = a[i];
        a[i] = r;
        i = j;
    }
    return r;    
 } 

void mix(int x,int y)      //混合 
{
    int fx = root(x),fy = root(y);
    if(fx != fy)
        a[fy] = fx;        //根节点的值覆盖 
}

int main()
{
    int i,j,t1,t2;
//    memset(a,0,sizeof(a));        //过程中超时了,除去这一条就AC了 
    cin>>n>>m;
    for(i = 1;i <= n;i++)
        a[i] = i;
    for(i = 1;i <= m;i++)
    {
        cin>>ci>>di;
        mix(ci,di);
    }
    cin>>l;
    for(i = 1;i <= l;i++)
    {
        cin>>t1>>t2;
        if(root(t1) != root(t2))
            cout<<"They aren't relative!"<<endl;
        else
            cout<<"They are relative!"<<endl;
    }
    
    return 0;
 } 

这是自学的并查集,然后在oj上敲的题。有关并查集的学习可以百度。

                                                                           -----15:44:28 2017-06-10

转载于:https://www.cnblogs.com/jdemarryme/p/6978986.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值