【题目链接】
【思路要点】
- 离散化变量名,用并查集将相等的变量并在一起。
- 若有不等的变量被并在了一起,答案为NO,否则答案为YES。
- 时间复杂度\(O(TNLogN)\)。
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 200005; template <typename T> void chkmax(T &x, T y) {x = max(x, y); } template <typename T> void chkmin(T &x, T y) {x = min(x, y); } template <typename T> void read(T &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } template <typename T> void write(T x) { if (x < 0) x = -x, putchar('-'); if (x > 9) write(x / 10); putchar(x % 10 + '0'); } template <typename T> void writeln(T x) { write(x); puts(""); } int n, tot, f[MAXN]; int x[MAXN], y[MAXN], t[MAXN]; map <int, int> mp; int F(int x) { if (f[x] == x) return x; else return f[x] = F(f[x]); } int main() { int T; read(T); while (T--) { read(n); mp.clear(); tot = 0; for (int i = 1; i <= n; i++) { read(x[i]), read(y[i]), read(t[i]); if (mp.count(x[i])) x[i] = mp[x[i]]; else x[i] = mp[x[i]] = ++tot; if (mp.count(y[i])) y[i] = mp[y[i]]; else y[i] = mp[y[i]] = ++tot; } for (int i = 1; i <= tot; i++) f[i] = i; for (int i = 1; i <= n; i++) if (t[i] == 1) f[F(x[i])] = F(y[i]); bool ans = true; for (int i = 1; i <= n; i++) if (t[i] == 0 && F(x[i]) == F(y[i])) ans = false; if (ans) printf("YES\n"); else printf("NO\n"); } return 0; }