码迷,mamicode.com
首页 > 其他好文 > 详细

并查集 P3367 【模板】并查集

时间:2019-04-23 19:27:13      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:oid   blank   back   tps   pac   div   i++   return   algo   

P3367 【模板】并查集

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
using namespace std;
int n,m,zi,xi,yi;
int father[10001];
int find(int x)  //寻找根结点并压缩路径
{
    if(father[x]!=x) father[x]=find(father[x]);
    return father[x];
}
void unionn(int x,int y) //合并两个集合
{
    x=find(x);
    y=find(y);
    father[y]=x;
}
bool judge(int x,int y)  //判断元素是否属于同一集合
{
    x=find(x);
    y=find(y);
    if(x==y)
      return true;
    else 
      return false;
}
int caozuo(int z,int x,int y)
{
    if(z==1)
        unionn(x,y);
    if(z==2)
    {
        if(judge(x,y))
          printf("Y\n");
        else
          printf("N\n");
    }
}
int main()
{
    scanf("%d%d",&n,&m);

    for(int i=1;i<=n;i++)  //初始化
      father[i]=i;for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&zi,&xi,&yi);
        caozuo(zi,xi,yi);
    }
    
    return 0;
    
}

 

并查集 P3367 【模板】并查集

标签:oid   blank   back   tps   pac   div   i++   return   algo   

原文地址:https://www.cnblogs.com/xiaoyezi-wink/p/10758162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!