Cod sursa(job #2023333)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 18 septembrie 2017 19:13:02
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream f("2sat.in");
ofstream g("2sat.out");

const int N = 200005;
vector <int> ls[N], lsi[N];
bool viz[N], val[N], FAIL;
int n, m, i, j, x, y, S[N];

int Not(int x) {
    if (x > n)
        return x-n;
    else return x+n;
}

void dfs1(int x) {
    int l = ls[x].size(), i, y;
    viz[x] = 1;
    for (i = 0; i < l; i++) {
        y = ls[x][i];
        if (viz[y]) continue;
        dfs1(y);
    }
    S[++m] = x;
}

void dfs2(int x) {
    int l = lsi[x].size(), i, y;
    if (val[x]) {
        FAIL = 1;
        return;
    }
    val[Not(x)] = 1;
    viz[x] = 0;
    for (i = 0; i < l; i++) {
        y = lsi[x][i];
        if (viz[y] == 0) continue;
        dfs2(y);
    }
}

int main() {
    f >> n >> m;
    while (m--) {
        f >> x >> y;
        if (x < 0) x = -x+n;
        if (y < 0) y = -y+n;

        ls[Not(x)].push_back(y);
        ls[Not(y)].push_back(x);
        lsi[x].push_back(Not(y));
        lsi[y].push_back(Not(x));
    }

    for (i = 1; i <= 2*n; i++)
        if (viz[i] == 0)
            dfs1(i);

    for (i = 2*n; i >= 1; i--)
        if (viz[S[i]] && viz[Not(S[i])])
            dfs2(S[i]);

    if (FAIL)
        g << -1;
    else for (i = 1; i <= n; i++)
        g << val[i] << ' ';
}