Cod sursa(job #2058201)

Utilizator MaligMamaliga cu smantana Malig Data 5 noiembrie 2017 11:51:49
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.39 kb
#include <bits/stdc++.h>

#if 0
#define pv(x) cout<<#x<<" = "<<x<<"; "
#define pn cout<<"\n"
#else
#define pv(x)
#define pn
#endif

using namespace std;
ifstream in("2sat.in");
ofstream out("2sat.out");

using ll = long long;
using ull = unsigned long long;
using ui = unsigned int;
#define pb push_back
#define mp make_pair
const int NMax = 2e5 + 5;
const ll inf = 1e18 + 5;
const int mod = 100003;
using zint = int;

int N,M,nrComp;
bool vis[NMax];
int compOf[NMax],val[NMax];
vector<int> v[NMax],rev[NMax],comp[NMax];
stack<int> st;

void dfs(int);
void getComp(int);
void setVal(int);

#define neg(x) ((x <= N) ? x+N : x-N)
int main() {
    in>>N>>M;
    for (int i=1;i <= M;++i) {
        int x,y;
        in>>x>>y;

        if (x < 0) {
            x = -x + N;
        }

        if (y < 0) {
            y = -y + N;
        }

        v[neg(x)].pb(y);
        rev[y].pb(neg(x));
        v[neg(y)].pb(x);
        rev[x].pb(neg(y));
    }

    for (int i=1;i <= 2*N;++i) {
        if (vis[i]) {
            continue;
        }

        dfs(i);
    }

    while (st.size()) {
        int node = st.top();
        st.pop();

        if (compOf[node]) {
            continue;
        }

        ++nrComp;
        getComp(node);
    }


    for (int i=1;i <= 2*N;++i) {
        val[i] = val[neg(i)] = -1;
    }

    for (int i=1;i <= nrComp;++i) {
        setVal(i);
    }

    bool ans = true;
    for (int i=1;i <= N;++i) {
        if (compOf[i] == compOf[neg(i)]) {
            ans = false;
            break;
        }
    }

    if (ans) {
        for (int i=1;i <= N;++i) {
            out<<val[i]<<' ';
        }
    }
    else {
        out<<"-1\n";
    }

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

void dfs(int node) {
    vis[node] = true;

    for (int nxt : v[node]) {
        if (vis[nxt]) {
            continue;
        }

        dfs(nxt);
    }

    st.push(node);
}

void getComp(int node) {
    comp[nrComp].pb(node);
    compOf[node] = nrComp;

    for (int nxt : rev[node]) {
        if (compOf[nxt]) {
            continue;
        }

        getComp(nxt);
    }
}

void setVal(int c) {
    int node = comp[c][0];

    if (val[node] != -1 || val[neg(node)] != -1) {
        return;
    }

    for (int node : comp[c]) {
        val[node] = 0;
        val[neg(node)] = 1;
    }
}