[BZOJ4195][NOI2015]程序自动分析(离散化+并查集)

首先将所有的 i j离散化。
先处理相等的条件。因为相等具有传递性,所以这里用并查集维护相等关系,在同一个连通块中的变量全部相等。即连边 (i,j)
然后处理不等的条件。可以发现,如果 i j在同一个连通块里,那么就同时存在 xi=xj xiyi ,这显然是矛盾的。所以对于所有的不等条件,如果存在一个条件的 i j在同一个连通块里,那么不可以被满足,否则可以被满足。
代码:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
    int res = 0; bool bo = 0; char c;
    while (((c = getchar()) < '0' || c > '9') && c != '-');
    if (c == '-') bo = 1; else res = c - 48;
    while ((c = getchar()) >= '0' && c <= '9')
        res = (res << 3) + (res << 1) + (c - 48);
    return bo ? ~res + 1 : res;
}
const int N = 2e5 + 5;
int n, m, fa[N], a[N];
struct cyx {
    int x, y, op;
} que[N];
int cx(int x) {
    if (fa[x] != x) fa[x] = cx(fa[x]);
    return fa[x];
}
void zm(int x, int y) {
    int ix = cx(x), iy = cx(y);
    if (ix != iy) fa[iy] = ix;
}
void work() {
    int i, tot = 0; n = read();
    for (i = 1; i <= n; i++) a[++tot] = que[i].x = read(),
        a[++tot] = que[i].y = read(), que[i].op = read();
    sort(a + 1, a + tot + 1); m = unique(a + 1, a + tot + 1) - a - 1;
    for (i = 1; i <= n; i++) {
        que[i].x = lower_bound(a + 1, a + m + 1, que[i].x) - a;
        que[i].y = lower_bound(a + 1, a + m + 1, que[i].y) - a;
    }
    for (i = 1; i <= m; i++) fa[i] = i;
    for (i = 1; i <= n; i++) if (que[i].op == 1)
        zm(que[i].x, que[i].y);
    for (i = 1; i <= n; i++) if (que[i].op == 0 && cx(que[i].x) == cx(que[i].y))
        return (void) (puts("NO")); puts("YES");
}
int main() {
    int T = read();
    while (T--) work();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值