776D - The Door Problem - CodeForces Solution


2-sat dfs and similar dsu graphs *2000

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
 
using namespace std;
 
#define MOD 1000000007
#define mod(x, m) (((x % m) + m) % m)
#define mxn 200005
#define mxm 100005
#define f first
#define s second
#define pb push_back
#define es " "
#define endl "\n"
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3f
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<pii, int> pip;
 
int n, m, v[mxn], viz[mxn][2], memo[mxn], comp[mxn];
vector<int> vec[mxn], vec2[mxn], st;

void dfs(int x){
    memo[x]=1;
    for(int i:vec[x]){
        if(!memo[i]) dfs(i);
    }
    st.pb(x);
}
void dfs2(int x, int c){
    comp[x]=c;
    for(int i:vec2[x]){
        if(!comp[i]) dfs2(i, c);
    }
}

void add(int x, int sx, int y, int sy){
    vec[x+m*sx].pb(y+m*(!sy));
    vec[y+m*sy].pb(x+m*(!sx));

    vec2[y+m*(!sy)].pb(x+m*sx);
    vec2[x+m*(!sx)].pb(y+m*sy);
}

int main(){
    fastio;
    cin >> n >> m;
    for(int i=1; i<=n; i++){
        cin >> v[i];
    }
    for(int i=1; i<=m; i++){
        int k;
        cin >> k;
        for(int j=0; j<k; j++){
            int x;
            cin >> x;
            if(!viz[x][0]) viz[x][0]=i;
            else viz[x][1]=i;
        }
    }
    for(int i=1; i<=n; i++){
        if(v[i]){
            add(viz[i][0], 1, viz[i][1], 0);
            add(viz[i][0], 0, viz[i][1], 1);
        }else{
            add(viz[i][0], 1, viz[i][1], 1);
            add(viz[i][0], 0, viz[i][1], 0);
        }
    }
    for(int i=1; i<=2*m; i++){
        if(!memo[i]) dfs(i);
    }
    int cont=0;
    for(int i=2*m-1; i>=0; i--){
        if(!comp[st[i]]){
            dfs2(st[i], ++cont);
        }
    }
    
    for(int i=1; i<=m; i++){
        if(comp[i]==comp[i+m]){
            cout << "NO" << endl;
            return 0;
        }
    }
    cout << "YES" << endl;
    return 0;
}


Comments

Submit
0 Comments
More Questions

688B - Lovely Palindromes
66B - Petya and Countryside
1557B - Moamen and k-subarrays
540A - Combination Lock
1553C - Penalty
1474E - What Is It
1335B - Construct the String
1004B - Sonya and Exhibition
1397A - Juggling Letters
985C - Liebig's Barrels
115A - Party
746B - Decoding
1424G - Years
1663A - Who Tested
1073B - Vasya and Books
195B - After Training
455A - Boredom
1099A - Snowball
1651D - Nearest Excluded Points
599A - Patrick and Shopping
237A - Free Cash
1615B - And It's Non-Zero
1619E - MEX and Increments
34B - Sale
1436A - Reorder
1363C - Game On Leaves
1373C - Pluses and Minuses
1173B - Nauuo and Chess
318B - Strings of Power
1625A - Ancient Civilization