Cod sursa(job #2528415)

Utilizator radugheoRadu Mihai Gheorghe radugheo Data 21 ianuarie 2020 20:45:40
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <bits/stdc++.h>
#define DIM 200005

using namespace std;

ifstream fin  ("2sat.in");
ofstream fout ("2sat.out");

int n, m, a, b, k, cnt;
int sol[DIM], low[DIM], niv[DIM];

bitset <DIM> f, prezentStiva;

vector <int> L[DIM];

stack <int> stec;

set <int> s;

void dfs (int nod){
    int don;
    f[nod] = 1;
    stec.push(nod);
    prezentStiva[nod] = 1;
    k++;
    low[nod] = niv[nod] = k;
    for (int i=0; i<L[nod].size(); i++){
        int vecin = L[nod][i];
        if (f[vecin] == 0){
            dfs (vecin);
            low[nod] = min (low[nod], niv[vecin]);
        }
        else{
            if (prezentStiva[vecin]){
                low[nod] = min (low[nod], niv[vecin]);
            }
        }
    }
    if (low[nod] == niv[nod]){
        s.clear();
        do{
            don = stec.top();
            stec.pop();
            prezentStiva[don] = 0;
            if ((don <= n && s.find(don + n) != s.end()) || (don > n && s.find(don - n) != s.end())){
               cnt = -1;
            }
            s.insert (don);
            if (sol[don] == 0){
                sol[don] = 1;
                if (don <= n){
                    sol[don+n] = -1;
                }
                else{
                    sol[don-n] = -1;
                }
            }
        } while (don != nod);
    }
}

int main(){
    fin >> n >> m;
    for (;m--;){
        fin >> a >> b;
        if (a > 0){
            if (b > 0){
                L[a+n].push_back(b);
                L[b+n].push_back(a);
            }
            else{
                L[a+n].push_back(-b+n);
                L[-b].push_back(a);
            }
        }
        else{
            if (b > 0){
                L[-a].push_back(b);
                L[b+n].push_back(-a+n);
            }
            else{
                L[-a].push_back(-b+n);
                L[-b].push_back(-a+n);
            }
        }
    }
    for (int i=1; i<=2*n; i++){
        if (!f[i]){
            dfs (i);
        }
    }
    if (cnt == -1){
        fout << -1;
        return 0;
    }
    for (int i=1; i<=n; i++){
        if (sol[i] != 1)
            fout << 0 << " ";
        else
            fout << sol[i] << " ";
    }
    return 0;
}