Cod sursa(job #2988125)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 3 martie 2023 17:31:13
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream cin("2sat.in");
ofstream cout("2sat.out");

const int MAX = 2e5 + 1;

vector <int> g[MAX] , gt[MAX];

int n , m , x , y , topo[MAX], in , ctc[MAX] , nctc;

bool viz[MAX];

void ts( int x ){

    viz[x] = 1;

    for(auto it : g[x]){

        if(!viz[it]) ts(it);
    }

    topo[++in] = x;
}

void dfs( int x ){

    ctc[x] = nctc;

    viz[x] = 0;

    for(auto it : gt[x]){

        if(viz[it]) dfs(it);
    }

}

int main()
{

    cin >> n >> m;

    while(m--){

        cin >> x >> y;

        if(x < 0){

            x = x*(-1);
            x = x+n;
        }

        if(y < 0){

            y = y*(-1);
            y = y+n;
        }

        if(x > n){

            g[x-n].push_back(y);

            gt[y].push_back(x-n);

        }else{

            g[x+n].push_back(y);

            gt[y].push_back(x+n);
        }

        if(y > n){

            g[y-n].push_back(x);

            gt[x].push_back(y-n);

        }else{

            g[y+n].push_back(x);

            gt[x].push_back(y+n);
        }

    }

    for(int i = 1 ; i <= 2*n ; i++){

        if(!viz[i]){ ts(i); }
    }

    for(int i = in ; i ; i--){

        if(viz[topo[i]]){

            nctc++;

            dfs(topo[i]);
        }
    }

    for(int i = 1 ; i <= n ; i++){

        if(ctc[i] == ctc[i+n]){

            cout << -1;

            exit(0);
        }
    }

    for(int i = 1 ; i <= n ; i++){

        cout << (ctc[i+n] < ctc[i]) << ' ';
    }

    return 0;
}