并查集模板

匿名 (未验证) 提交于 2019-12-02 23:34:01

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; }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!