标签:
今天一定彻底弄懂 带权并查集
1 #include <iostream> 2 #include <cstdio> 3 #include <fstream> 4 #include <algorithm> 5 #include <cmath> 6 #include <deque> 7 #include <vector> 8 #include <queue> 9 #include <string> 10 #include <cstring> 11 #include <map> 12 #include <stack> 13 #include <set> 14 #define LL long long 15 #define INF 0x3f3f3f3f 16 //#define OPEN_FILE 17 #define MAXN 50005 18 using namespace std; 19 int n, k; 20 int father[MAXN]; 21 int ranK[MAXN]; 22 int find(int x){ 23 if (x == father[x]) return x; 24 int y = father[x]; 25 father[x] = find(father[x]); 26 ranK[x] = (ranK[x] + ranK[y]) % 3; 27 return father[x]; 28 } 29 void union_set(int x, int y, int z){ 30 int a = father[x], b = father[y]; 31 father[a] = b; 32 ranK[a] = (z + ranK[y] - ranK[x] + 3) % 3; 33 } 34 int main() 35 { 36 #ifdef OPEN_FILE 37 freopen("in.txt", "r", stdin); 38 freopen("out.txt", "w", stdout); 39 #endif // OPEN_FILE 40 scanf("%d%d", &n, &k); 41 for (int i = 1; i <= n; i++){ 42 father[i] = i; 43 } 44 memset(ranK, 0, sizeof(ranK)); 45 int x, y, z; 46 int cnt = 0; 47 for (int i = 1; i <= k; i++){ 48 scanf("%d%d%d", &z, &x, &y); 49 if (x > n || y > n){ 50 cnt++; 51 continue; 52 } 53 if (x == y && z == 2){ 54 cnt++; 55 continue; 56 } 57 int a = find(x), b = find(y); 58 if (a == b && ranK[x] != (z - 1 + ranK[y]) % 3){ 59 cnt++; 60 } 61 if (a != b){ 62 union_set(x, y, z - 1); 63 } 64 } 65 printf("%d\n", cnt); 66 }
标签:
原文地址:http://www.cnblogs.com/macinchang/p/4694362.html