Cod sursa(job #2044103)

Utilizator stefanzzzStefan Popa stefanzzz Data 20 octombrie 2017 21:47:56
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#define MAXN 100005
using namespace std;

int n, m, sol[2 * MAXN];
vector<int> G[2 * MAXN], GT[2 * MAXN];
bool used[2 * MAXN];
vector<int> topSort;

int neg(int x) {
    return ((x <= n) ? (x + n) : (x - n));
}

void DFS(int u) {
    used[u] = 1;

    for (auto x: G[u]) {
        if (!used[x])
            DFS(x);
    }

    topSort.push_back(u);
}

void DFST(int u) {
    used[u] = 1;
    if (used[neg(u)]) {
        cout << "-1\n";
        exit(0);
    }
    sol[neg(u)] = 1;

    for (auto x: GT[u]) {
        if (!used[x])
            DFST(x);
    }
}

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

    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        cin >> x >> y;
        if (x < 0) x = neg(-x);
        if (y < 0) y = neg(-y);

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

    for (int i = 1; i <= 2 * n; ++i) {
        if (!used[i])
            DFS(i);
    }

    reverse(topSort.begin(), topSort.end());
    memset(used, 0, sizeof(used));

    for (auto x: topSort) {
        if (!used[x] && !used[neg(x)])
            DFST(x);
    }

    for (int i = 1; i <= n; ++i)
        cout << sol[i] << " ";
    cout << "\n";

    return 0;
}