题目思路并不复杂…只要想到并查集就好…
不过还有一点…xi和xj数可能很大,那么我们是不可能搞那么大的数组的…所有应该利用map或者哈希之类的离散化到一个比较小的范围内…
对于所有要求相等的条件,把xi和xj合并,所有相等的都合并之后,开始检查不相等的条件,此时如果发现条件中有一组数之前已经被合并了,那么说明这个问询是有矛盾存在的。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
using namespace std;
struct query {
int x, y;
};
query q[1000001];
int par[2000005];
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;
par[y] = x;
}
int main()
{
int t, n, i, j;
cin >> t;
while (t--) {
cin >> n; int cnt1 =0, cnt2 = 0;
for (i = 1; i <= 2*n; i++)
par[i] = i;
map<int, int>hash1;
map<int, int>::iterator iter;
for (i = 1; i <= n; i++) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
if ((iter = hash1.find(a)) == hash1.end()) {
hash1.insert(pair<int, int>(a, ++cnt1)); a = cnt1;
}
else
a = iter->second;
if ((iter = hash1.find(b)) == hash1.end()) {
hash1.insert(pair<int, int>(b, ++cnt1)); b = cnt1;
}
else
b = iter->second;
if (c == 1)
//q1[++cnt1].x = a, q1[cnt1].y = b;
unite(a, b);
else
q[++cnt2].x = a, q[cnt2].y = b;
}
bool check = true;
for (i = 1; i <= cnt2; i++) {
if (find(q[i].x) == find(q[i].y)) {
check = false; break;
}
}
if (check)cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}