Cod sursa(job #3304523)

Utilizator Mihai_OctMihai Octavian Mihai_Oct Data 24 iulie 2025 14:33:40
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

#define ST_DIO 0
#if ST_DIO
    #define fin cin
    #define fout cout
#else
    ifstream fin("2sat.in");
    ofstream fout("2sat.out");
#endif  // ST_DIO

int n, m, i, j, comp;
vector<int> gr[2][200002];
stack<int> st;

int scc[200002];

bool fr[200002];

static inline void DFS1(int nod) {
    fr[nod] = true;
    for(int urm : gr[0][nod]) {
        if(!fr[urm]) DFS1(urm);
    }
    st.push(nod);
}

static inline void DFS2(int nod, const int cmp) {
    fr[nod] = true;
    scc[nod] = cmp;
    for(int urm : gr[1][nod]) {
        if(!fr[urm]) DFS2(urm, cmp);
    }
}

int main() {
    fin >> n >> m;
    for(i = 1; i <= m; i++) {
        int x, y, xx, yy;
        fin >> x >> y;
        if(x < 0) {
            xx = -x;
            x = xx + n;
        }
        else xx = x + n;

        if(y < 0) {
            yy = -y;
            y = yy + n;
        }
        else yy = y + n;

        gr[0][xx].push_back(y);
        gr[0][yy].push_back(x);
        gr[1][y].push_back(xx);
        gr[1][x].push_back(yy);
    }

    for(i = 1; i <= 2 * n; i++) {
        if(!fr[i]) DFS1(i);
    }

    memset(fr, 0, sizeof(fr));
    while(!st.empty()) {
        int nod = st.top();
        st.pop();

        if(!fr[nod]) {
            DFS2(nod, ++comp);
        }
    }

    for(i = 1; i <= n; i++) {
        if(scc[i] == scc[i + n]) {
            fout << -1;
            return 0;
        }
    }

    for(i = 1; i <= n; i++) {
        fout << (scc[i] > scc[i + n]) << " ";
    }

    return 0;
}