洛谷 P3367 【模板】並查集
阿新 • • 發佈:2017-06-29
ret stream pri amp 是的 color div -a std
輸出樣例#1:
題目描述
如題,現在有一個並查集,你需要完成合並和查詢操作。
輸入輸出格式
輸入格式:第一行包含兩個整數N、M,表示共有N個元素和M個操作。
接下來M行,每行包含三個整數Zi、Xi、Yi
當Zi=1時,將Xi與Yi所在的集合合並
當Zi=2時,輸出Xi與Yi是否在同一集合內,是的話輸出Y;否則話輸出N
輸出格式:如上,對於每一個Zi=2的操作,都有一行輸出,每行包含一個大寫字母,為Y或者N
輸入輸出樣例
輸入樣例#1:4 7 2 1 2 1 1 2 2 1 2 1 3 4 2 1 4 1 2 3 2 1 4
N Y N Y
說明
時空限制:1000ms,128M
數據規模:
對於30%的數據,N<=10,M<=20;
對於70%的數據,N<=100,M<=1000;
對於100%的數據,N<=10000,M<=200000。
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 5 using namespace std; 6 int fa[10005]; 7 int n,m; 8 9 void init()10 { 11 for(int i = 1;i <= n;i ++) 12 { 13 fa[i] = i; 14 } 15 } 16 17 int find(int x) 18 { 19 if(fa[x] == x) 20 return x; 21 return fa[x] = find(fa[x]); 22 }; 23 24 void merge(int x,int y) 25 { 26 int a = find(x); 27 int b = find(y); 28fa[a] = b; 29 } 30 31 int jud(int x,int y) 32 { 33 int a = find(x); 34 int b = find(y); 35 if(a == b) 36 return 1; 37 else 38 return 0; 39 } 40 41 int main() 42 { 43 scanf("%d%d",&n,&m); 44 init(); 45 int op,l,r; 46 for(int i = 1;i <= m;i ++) 47 { 48 scanf("%d%d%d",&op,&l,&r); 49 if(op == 1) 50 { 51 merge(l,r); 52 } 53 if(op == 2) 54 { 55 int t = jud(l,r); 56 if(t) 57 printf("Y\n"); 58 else 59 printf("N\n"); 60 } 61 } 62 return 0; 63 }
洛谷 P3367 【模板】並查集