题目链接 https://www.luogu.com.cn/problem/P1955
AC代码
#include<iostream> #include <algorithm> #include<cstdio> using namespace std; typedef long long ll; const int N = 1e6 + 5; int a[N][3]; int b[N + N]; int par[N+N]; int rank[N +N]; void init(int n) { for (int i = 0; i < n; i++) { par[i] = i; rank[i] = 0; } } int find(int x) { if (par[x] == x) { return x; }else return par[x] = find(par[x]); } void unite(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (rank[x] < rank[y]) { par[x] = y; } else { par[y] = x; if (rank[x] == rank[y]) rank[x]++; } } bool same(int x, int y) { return find(x) == find(y); } int main() { ios::sync_with_stdio(false);cin.tie(NULL); int t; cin >> t; while (t--) { int n; int j = 0; cin >> n; string s = "YES"; for (int i = 0; i < n; i++) { cin >> a[i][0] >> a[i][1] >> a[i][2]; b[j++] = a[i][0]; b[j++] = a[i][1]; } sort(b, b + j); //debug int size = unique(b, b + j) - b; for (int i = 0; i < n; i++) { a[i][0] = lower_bound(b, b + size, a[i][0]) - b; a[i][1] = lower_bound(b, b + size, a[i][1]) - b; } init(N+N); for (int i = 0; i < n; i++) { if (a[i][2] == 1) unite(a[i][0],a[i][1]); } for (int i = 0; i < n; i++) { if (a[i][2] == 0) { if (same(a[i][0], a[i][1])) { //debug s = "NO"; break; } } } cout << s<< endl; } }