您的位置:首页 > 其它

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

2017-10-15 16:00 429 查看
首先将所有的i和j离散化。

先处理相等的条件。因为相等具有传递性,所以这里用并查集维护相等关系,在同一个连通块中的变量全部相等。即连边(i,j)。

然后处理不等的条件。可以发现,如果i和j在同一个连通块里,那么就同时存在xi=xj和xi≠yi,这显然是矛盾的。所以对于所有的不等条件,如果存在一个条件的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
, a
;
struct cyx {
int x, y, op;
} que
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: