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

来源:互联网 发布:js append 编辑:程序博客网 时间:2024/05/17 00:02

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

#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;}
阅读全文
0 0