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

并查集模板

时间:2019-05-21 19:42:40      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:mes   stream   line   turn   utc   int   并查集   bin   getchar   

推荐题目:P3367 【模板】并查集

该题的缺点:数据不够水
本蒟蒻实在是太弱了,不会!
推荐一篇文章:浅谈并查集优化
Code:

#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
using namespace std;
int n,m,bz;
int father[200001];
int find(int x) {
    if(x==father[x]) return x;
    return father[x]=find(father[x]);
}
void unnio(int x,int y) {
    father[y]=x;
}
inline int read() {
    bool f=0;
    int x=0;
    char c=getchar();
    while(c<'0'||c>'9') {
        if(c=='-') f=!f;
        c=getchar();
    }
    while(c>='0'&&c<='9') {
        x=x*10+c-'0';
        c=getchar();
    }
    return f?-x:x;
}
inline void write(int x) {
    if(x<0) {
        putchar('-');
        write(-x);
    } else {
        if(x/10) write(x/10);
        putchar(x%10+'0');
    }
}

int main() {
    n=read();
    m=read();
    for(int i=1; i<=n; ++i)
        father[i]=i;
    int x,y;
    for(int i=1; i<=m; ++i) {
        bz=read();
        x=read();
        y=read();
        if(bz==1)
        {
            int bz1=find(x);
            int bz2=find(y);
            if(bz1!=bz2) unnio(bz1,bz2);
        }
        else
        {
            if(find(x)==find(y)) printf("Y\n");
            else printf("N\n");
        }
    }
    return 0;
}

并查集模板

标签:mes   stream   line   turn   utc   int   并查集   bin   getchar   

原文地址:https://www.cnblogs.com/poi-bolg-poi/p/10901534.html

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