Cod sursa(job #1831725)

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

const int NMAX = 2e5 + 5;

vector<int> stk;
bitset<NMAX> fins, instk;
int hgt, cbp, n;

vector<int> g[NMAX];
int lvl[NMAX], low[NMAX], ctc[NMAX], val[NMAX];

int inv(int x) {
    if (x <= n) return n + x;
    if (x > n) return x - n; }

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

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

    if (lvl[u] == low[u]) {
        int top;
        ++cbp;
        do {
            top = stk.back();
            stk.pop_back();
            instk[top] = false;
            ctc[top] = cbp;

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

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

    int m, x, y;

    scanf("%d%d", &n, &m);
    while (m--) {
        scanf("%d%d", &x, &y);
        x = (x < 0)  ? (n - x) : x;
        y = (y < 0)  ? (n - y) : y;
        g[inv(x)].push_back(y);
        g[inv(y)].push_back(x); }

    for (int i = 1; i <= n; ++i)
        if (lvl[i] == 0)
            sat(i);

    for (int i = 1; i <= n; ++i) {
        if (ctc[i] == ctc[inv(i)]) {
            printf("-1\n");
            return 0; } }

    for (int i = 1; i <= n; ++i)
        printf("%d ", int(val[i] > 0));
    printf("\n");

    return 0; }