BZOJ 4195 && NOI 2015 [并查集]

假设 x1,x2,x3, 代表程序中出现的变量,给定 n 个形如xi=xj xixj 的变量相等/不等的约束条件,请判定是否可以分别为每一个变量赋予恰当的值,使得上述所有约束条件同时被满足。

并查集真心水啊QAQ。
不过毕竟编译提交啥的都一次就通过了还是很愉悦的(本来就该这样?)
水一发QAQ

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

inline char get(void) {
    static char buf[1000000], *p1 = buf, *p2 = buf;
    if (p1 == p2) {
        p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin);
        if (p1 == p2) return EOF;
    }
    return *p1++;
}
inline void read(int &x) {
    x = 0; char c = get(); int sign = 1;
    for (; c < '0' || c > '9'; c = get()) if(c == '-') sign = 0;
    for (; c >= '0' && c <= '9'; x = (x << 1) + (x << 3) + c - '0', c = get());
    x = sign ? x : -x;
}

const int N = 1001010;

struct event {
    int x, y;
    bool eq;
    event(int _x = 0, int _y = 0, bool e = 0):x(_x), y(_y), eq(e) {}
    friend bool operator <(const event &a, const event &b) {
        return a.eq > b.eq;
    }
};
event a[N];
int mp[N << 1], fa[N << 1], f[N << 1];
int n, m, opt, test, cnt, x, y, l, r, mid, f1, f2, p;

inline int find(int x) {
    l = 0; r = cnt - 1;
    while (l < r) {
        mid = (l + r) >> 1;
        if (x <= mp[mid]) r = mid;
        else l = mid + 1;
    }
    return r + 1;
}
inline int getfa(int x) {
    return x == f[x] ? x : f[x] = getfa(f[x]);
}

int main(void) {
    freopen("1.in", "r", stdin);
    read(test);
    while (test--) {
        read(n); cnt = 0;
        for (int i = 0; i < n; i++) {
            read(x); read(y); read(opt);
            mp[cnt++] = x; mp[cnt++] = y;
            a[i] = event(x, y, opt);
        }
        sort(mp, mp + cnt);
        cnt = unique(mp, mp + cnt) - mp;
        sort(a, a + n);
        for (int i = 1; i <= cnt; i++) f[i] = i;
        for (p = 0; a[p].eq && p < n; p++) {
            f1 = getfa(find(a[p].x));
            f2 = getfa(find(a[p].y));
            if (f1 != f2) f[f1] = f2;
        }
        for (; p < n; p++) {
            if (getfa(find(a[p].x)) == getfa(find(a[p].y))) {
                puts("NO"); goto W;
            }
        }
        puts("YES"); W:;
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值