Cod sursa(job #1503231)

Utilizator stefanzzzStefan Popa stefanzzz Data 15 octombrie 2015 19:08:59
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <stdio.h>
#include <vector>
#include <string.h>
#define MAXN 100005
using namespace std;

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

inline int neg(int x) {
    return (x > n)?(x - n):(x + n);
}

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

void DFST(int u) {
    uz[u] = 1;
    if(uz[neg(u)]) haveSol = 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 = n - x;
        if(y < 0) y = n - y;

        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);

    memset(uz, 0, sizeof(uz));

    for(int i = ord.size() - 1; i >= 0 && haveSol; i--)
        if(!uz[ord[i]] && !uz[neg(ord[i])])
            DFST(ord[i]);

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

    return 0;
}