Cod sursa(job #1487934)

Utilizator SmarandaMaria Pandele Smaranda Data 17 septembrie 2015 17:34:16
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>

using namespace std;

const int N = 200002;

vector <int> graph [N], graph2 [N];
stack <int> st;
bool used [N], ans;
int n, value [N];

void dfs (int x) {
    vector <int> :: iterator it;

    used [x] = 1;
    for (it = graph [x].begin (); it != graph [x].end (); ++ it)
        if (!used [*it])
            dfs (*it);
    st.push (x);
}

void dfs2 (int x) {
    vector <int> :: iterator it;

    used [x] = 1;
    if (value [x]) {
        ans = 0;
        return;
    }
    value [x] = 0;
    if (x <= n)
        value [n + x] = 1;
    else
        value [x - n] = 1;
    for (it = graph2 [x].begin (); it != graph2 [x].end () && ans; ++ it)
        if (!used [*it])
            dfs2 (*it);
}

int main () {
    int i,  a, b, m, ineg;
    vector <int> :: iterator it;

    freopen ("2sat.in", "r", stdin);
    freopen ("2sat.out", "w", stdout);

    scanf ("%d%d", &n, &m);
    for (i = 1; i <= m; i ++) {
        scanf ("%d%d", &a, &b);
        if (a < 0)
            a = n - a;
        if (b < 0)
            b = n - b;
        if (b <= n) {
            graph2 [a].push_back (n + b);
            graph [n + b].push_back (a);
        }
        else {
            graph2 [a].push_back (b - n);
            graph [b - n].push_back (a);
        }
        if (a <= n) {
            graph2 [b].push_back (n + a);
            graph [n + a].push_back (b);
        }
        else {
            graph2 [b].push_back (a - n);
            graph [a - n].push_back (b);
        }
    }
    for (i = 1; i <= 2 * n; i ++)
        if (!used [i])
            dfs (i);
    memset (used, 0, sizeof (used));
    ans = 1;
    while (!st.empty () && ans) {
        i = st.top ();
        if (i > n)
            ineg = i - n;
        else ineg = n + i;
        st.pop ();
        if (!used [i] && !used [ineg]) {
            dfs2 (i);
        }
    }
    if (ans == 0)
        printf ("-1");
    else for  (i = 1; i <= n; i ++)
            printf ("%d ", value [i]);
    printf ("\n");
    return 0;
}