题目链接:http://poj.org/problem?id=1182
题意:看不懂?退群吧
比平常的并查集加了一个判断集合间关系的操作;
开一个数组记录当前点所在集合的次序(第几个集合)用012表示
比较简单的思路,不过体现了并查集的精妙
#include <iostream> #include <cstring> #include <cstdio> using namespace std; int dad[500005]; int st[50005]; int find(int x) { if(dad[x] != x) { int t = dad[x]; dad[x] = find(t); st[x] += st[t]; st[x] %= 3; } return dad[x]; } int main() { #ifndef ONLINE_JUDGE freopen("D:\fengyu\Jiang_C\.vscode\in.txt","r",stdin); freopen("D:\fengyu\Jiang_C\.vscode\out.txt","w",stdout); #endif int n, k; cin >> n >> k; for (int i = 0; i <= n; i++) { dad[i] = i; st[i] = 0; } int d, x, y; int ans = 0; while (k--) { scanf("%d%d%d", &d, &x, &y); if (x>n|| y>n || d==2 && x==y) { ans++; continue; } int fx = find(x); int fy = find(y); if(fx==fy) { if(d==1 && st[x]!=st[y] || d==2 &&st[x]!=(st[y]+2)%3) { ans++; } } else { dad[fy] = fx; st[fy] = (st[x]+d-1+3-st[y])%3; } } cout << ans << endl; return 0; }