Codeforces 776D The Door Problem 【并查集】

来源:互联网 发布:淘宝爆款广告语 编辑:程序博客网 时间:2024/05/17 02:06

题目链接:http://codeforces.com/contest/776/problem/D

题意:
有一些锁,初始状态为ri,其中ri为1表示unlock,为0表示lock,给出锁与锁之间的关系,即拉一下第i个锁,与第i个锁相连的其它锁都要改变一下状态,问有没有可能让所有的锁都变成unlock状态(即都为1)

题解:
并查集维护即可,使x表示执行了第x号命令,x+m表示不执行第x号命令,维护即可。
P.S:这题评测时间真心长,请大家耐心等待。

代码:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <vector>using namespace std;typedef long long LL;const int inf = 1 << 26;vector<int> sav[200005]; int fath[400005], a[200005];int find(int x) {    if(fath[x] == x) return fath[x];    return fath[x] = find(fath[x]);}void merge(int x, int y) {    int fx = find(x), fy = find(y);    if(fx == fy) return ;    fath[fy] = fx;}int main(){    int n, m;    scanf("%d %d", &n, &m);    for ( int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);    for ( int i = 1; i <= m; i ++ ) {        int x;        scanf("%d", &x);        for ( int j = 0; j < x; j ++ ) {            int y;            scanf("%d", &y);            sav[y].push_back(i);        }     }    for ( int i = 0; i <= 400000; i ++ ) fath[i] = i;    for ( int i = 1; i <= n; i ++ ) {        int x = sav[i][0], y = sav[i][1];        if(a[i]) {            merge(x, y);            merge(x+m, y+m);        } else {            merge(x+m, y);            merge(x, y+m);        }    }    for ( int i = 1; i <= m; i ++ ) {        if(find(i) == find(i+m)) {            puts("NO");            return 0;        }    }     puts("YES");    return 0;}
0 0