Cod sursa(job #2880081)

Utilizator uaichereuaichere uaichere Data 29 martie 2022 13:38:46
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>
#define NMAX 200005
using namespace std;
ifstream in("2sat.in");
ofstream out("2sat.out");

int n, m;
int viz[NMAX], comp[NMAX], cnt;
vector <int> G[NMAX], GT[NMAX];
stack <int> top;
void read() {
    in >> n >> m;
    int i = 0, j = 0, x = 0, y = 0;
    while(m--) {
        in >> i >> j;
        if(i < 0) {
            i = i*-2+1;
            x = i-1;
        }
        else {
            i *= 2;
            x = i+1;
        }
        if(j < 0) {
            j = j*-2+1;
            y = j-1;
        }
        else {
            j *= 2;
            y = j+1;
        }
        G[x].push_back(j);
        G[y].push_back(i);
        GT[j].push_back(x);
        GT[i].push_back(y);
    }
}

void dfs1(int k) {
    viz[k] = 1;
    for(auto i : G[k])
        if(viz[i] == 0)
            dfs1(i);
    top.push(k);
}

void dfs2(int k) {
    viz[k] = 2;
    comp[k] = cnt;
    for(auto i : GT[k])
        if(viz[i] == 1)
            dfs2(i);
}

void solve() {
    for(int i = 2; i <= 2*n+1; i++)
        if(viz[i] == 0)
            dfs1(i);
    while(!top.empty()) {
        int k = top.top();
        top.pop();
        if(viz[k] == 1) {
            cnt++;
            dfs2(k);
        }
    }
    bool ik = false;
    for(int i = 2; i <= 2*n+1 && !ik; i += 2) {
        if(comp[i] == comp[i+1])
            ik = true;
    }
    if(ik)
        out << -1;
    else {
        for(int i = 2; i <= 2*n+1 && !ik; i += 2)
            out << (comp[i] > comp[i+1]) << ' ';
    }
}

int main() {
    ios::sync_with_stdio(false);
    in.tie(0);
    out.tie(0);
    read();
    solve();

    in.close();
    out.close();
    return 0;
}