1 #include <bits/stdc++.h> 2 using namespace std; 3 template <class T> 4 inline void read(T &s) 5 { 6 s = 0; 7 int w = 1; 8 char ch = getchar(); 9 while (ch < '0' || ch > '9') 10 { 11 if (ch == '-') 12 w = -1; 13 ch = getchar(); 14 } 15 while (ch >= '0' && ch <= '9') 16 { 17 s = s * 10 + (ch ^ '0'); 18 ch = getchar(); 19 } 20 s *= w; 21 } 22 23 template <class T> 24 inline void write(T x) 25 { 26 if (x < 0){ 27 putchar('-'); 28 x = -x; 29 } 30 if (x > 9) 31 write(x / 10); 32 putchar(x % 10 + '0'); 33 } 34 const int N = 2e5 + 3; 35 int n, m, pre[N]; 36 int find(int x) // 路径压缩 + 找到根节点 37 { 38 if(pre[x] != x) pre[x] = find(pre[x]); 39 // 将x向上查找根节点过程中走过的所有点的父节点都标记为x对应的根节点,路径压缩 40 return pre[x]; 41 } 42 int main() 43 { 44 read(n), read(m); 45 for(int i = 1; i <= n; ++i) pre[i] = i; 46 while(m--){ 47 int z, x, y; 48 read(z), read(x), read(y); 49 switch(z){ 50 case 1: 51 pre[find(x)] = find(y); // 将x对应的根节点合并为y对应的根节点的儿子 52 // pre[x的根节点] = y的根节点 53 break; 54 case 2: 55 if(find(x) == find(y)) puts("Y"); 56 else puts("N"); 57 break; 58 } 59 } 60 // system("pause"); 61 return 0; 62 }
标签:pre,10,ch,洛谷,int,查集,read,P3367,节点 From: https://www.cnblogs.com/nijigasaki14/p/17847824.html