The Door Problem 并查集

传送门

题目描述

​有n个门和m个开关,每个开关可以控制任意多的门,每个门严格的只有两个开关控制,问能否通过操作某些开关使得所有门都打开。(给出门的初始状态)。

分析

一开始看的时候觉得是个2—sat问题,然后想了想感觉不太好建图,于是采用并查集的解法

我们可以把每个钥匙定义成两种状态,i和i + m,表示钥匙使用和未使用
如果某个门处于1状态,那么我们就要将两把钥匙同时使用或者同时不使用,也就是i,j之间连一条边,i + m和j + m之间连一条边,如果处于0状态,就在i和j + m之间连一条边,i + m和j之间连一条边

最后只需要判断联通的合法性就行了

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
int q[N];
int a[N][2];
int cnt[N];
int b[N];
int n,m;

int find(int x){
    
    
    if(q[x] != x) q[x] = find(q[x]);
    return q[x];
}

void merge(int x,int y){
    
    
    x = find(x),y = find(y);
    if(x != y) q[x] = y; 
}

int main(){
    
    
    scanf("%d%d",&n,&m);
    for(int i = 1;i <= n;i++) scanf("%d",&b[i]);
    for(int i = 1;i <= m;i++){
    
    
        int x,y;
        scanf("%d",&x);
        while(x--){
    
    
            scanf("%d",&y);
            a[y][cnt[y]++] = i;
        }
        q[i] = i;
        q[i + m] = i + m;
    }
    for(int i = 1;i <= n;i++){
    
    
        if(!b[i]) merge(a[i][0],a[i][1] + m),merge(a[i][1],a[i][0] + m);
        else merge(a[i][0],a[i][1]),merge(a[i][1] + m,a[i][0] + m);
    }
    for(int i = 1;i <= m;i++){
    
    
        if(find(i) == find(i + m)) {
    
    
            puts("NO");
            return 0;
        }
    }
    puts("YES");
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/

猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/112167274
今日推荐