Cod sursa(job #1470449)

Utilizator stefanzzzStefan Popa stefanzzz Data 11 august 2015 10:56:05
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <stdio.h>
#include <vector>
#define MAXN 100005
using namespace std;

int n, m, x, y;
vector<int> G[2 * MAXN], GT[2 * MAXN], v;
bool uz[2 * MAXN], sol[2 * MAXN], flag = 1;

inline int neg(int x) {
    if(x <= n) return x + n;
    return x - n;
}

void DFSP(int u) {
    uz[u] = 1;
    for(auto x: G[u])
        if(!uz[x])
            DFSP(x);
    v.push_back(u);
}

void DFST(int u) {
    uz[u] = 0;
    if(sol[u]) flag = 0;
    sol[u] = 0; sol[neg(u)] = 1;

    for(auto x: GT[u])
        if(uz[x])
            DFST(x);
}

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

    scanf("%d %d", &n, &m);
    for(int i = 1; i <= m; i++) {
        scanf("%d %d", &x, &y);
        if(x < 0) x = -x + n;
        if(y < 0) y = -y + n;

        G[neg(x)].push_back(y);
        G[neg(y)].push_back(x);
        GT[y].push_back(neg(x));
        GT[x].push_back(neg(y));
    }

    for(int i = 1; i <= 2 * n; i++)
        if(!uz[i])
            DFSP(i);

    while(!v.empty()) {
        x = v.back(); v.pop_back();
        while((!uz[x] || !uz[neg(x)]) && !v.empty()) {
            x = v.back();
            v.pop_back();
        }
        if(!uz[x] || !uz[neg(x)]) break;

        DFST(x);
    }

    if(!flag)
        printf("-1\n");
    else {
        for(int i = 1; i <= n; i++)
            printf("%d ", sol[i]);
        printf("\n");
    }

    return 0;
}