【BZOJ4195】【UOJ127】【NOI2015】程序自动分析

【题目链接】

【思路要点】

  • 离散化变量名,用并查集将相等的变量并在一起。
  • 若有不等的变量被并在了一起,答案为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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值