Cod sursa(job #1831705)

Utilizator oldatlantianSerban Cercelescu oldatlantian Data 18 decembrie 2016 16:33:42
Problema 2SAT Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1e5 + 5;

vector<int> stk;
bitset<2 * NMAX> fins;
int sbp;
bool nope;

vector<int> g[2 * NMAX];
int lvl[2 * NMAX], low[2 * NMAX];
char val[2 * NMAX];

#define g (g + NMAX)
#define val (val + NMAX)
#define fins(x) fins(x + NMAX)

void sat(int u) {
    stk.push_back(u);
    lvl[u] = low[u] = ++sbp;

    for (auto v: g[u]) {
        if (lvl[v] == 0)
            sat(v);
        low[u] = min(low[u], low[v]); }

    if (lvl[u] == low[u]) {
        int top;

        fins = 0;

        do {
            top = stk.back();
            fins[NMAX + top] = true;
            stk.pop_back();

            if (!val[top]) {
                val[top] = 1;
                val[-top] = -1; }

            if (fins[NMAX - top])
                nope = true; }
        while (top != u); } }

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

    int n, m, x, y;

    scanf("%d%d", &n, &m);
    while (m--) {
        scanf("%d%d", &x, &y);
        g[-x].push_back(y);
        g[-y].push_back(x); }

    for (int i = 1; i <= n && !nope; ++i) {
        if (lvl[i] == 0) {
            sat(i); } }

    if (nope) {
        printf("-1\n"); }
    else {
        for (int i = 1; i <= n; ++i)
            printf("%d ", int(val[i] > 0));
        printf("\n"); }

    return 0; }