带权并查集傻逼题
用拆点方法草过。
拆点代码:
# include <stdio.h> # include <string.h> int set[150005], n, k, d; int find(int x) { int s, temp; for (s=x; set[s]>=0; s=set[s]) ; while (s != x) { temp = set[x]; set[x] = s; x = temp; } return s; } void union_set(int x, int y) { x = find(x); y = find(y); int temp = set[x] + set[y]; if (x != y) { if (set[x] > set[y]) { set[x] = y; set[y] = temp; } else { set[y] = x; set[x] = temp; } } } int main (void) { int x, y, cnt=0; scanf("%d%d",&n,&k); memset(set,-1,sizeof(set)); while (k--) { scanf("%d%d%d",&d,&x,&y); if (x>n || y>n) { cnt++; continue; } if (d == 1) { if (find(x) == find(y+n) || find(x) == find(y+2*n)) { cnt++; } else { union_set(x,y); union_set(x+n,y+n); union_set(x+2*n,y+2*n); } } else { if (find(x) == find(y) || find(x) == find(y+2*n)) cnt++; else { union_set(x,y+n); union_set(x+n,y+n*2); union_set(x+n*2,y); } } } printf("%d\n",cnt); return 0; }
时间: 2024-10-15 03:08:30