Cod sursa(job #3142188)

Utilizator user12345user user user user12345 Data 20 iulie 2023 02:12:46
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <bits/stdc++.h>
using namespace std;

string fileName = "2sat";
ifstream fin(fileName + ".in");
ofstream fout(fileName + ".out");

int n, m, nrCtc;
vector <int> *g;
vector <int> v[200001];
int *ctc, *h, *top;
stack <int> S;
bool *inS, error = false;
int res[100001];

void sub(int nod, int height = 1) {

    h[nod] = top[nod] = height;
    S.push(nod);
    inS[nod] = true;

    for (auto &i : g[nod])
        if (!h[i])
            sub(i, height + 1), top[nod] = min(top[nod], top[i]);
        else if (inS[i])
            top[nod] = min(top[nod], top[i]);

    if (h[nod] == top[nod]) {

        int x;
        nrCtc++;

        do {

            x = S.top();
            S.pop();
            inS[x] = false;
            ctc[x] = nrCtc;
            if (ctc[x] == ctc[-x])
                error = true;

        }while (x != nod);
    }
}

int main() {

    g = new vector <int> [200011];
    g += 100001;
    ctc = new int[200011];
    ctc += 100001;
    inS = new bool[200011];
    inS += 100001;
    h = new int[200011];
    h += 100001;
    top = new int[200011];
    top += 100001;

    fin >> n >> m;

    for (int i = -n; i <= n; i++)
        ctc[i] = -1;

    for (int i = 1; i <= m; i++) {

        int x, y;
        fin >> x >> y;

        g[-x].push_back(y);
        g[-y].push_back(x);
    }

    for (int i = -n; i < 0; i++)
        if (h[i] == 0)
            sub(i);
    for (int i = 1; i <= n; i++)
        if (h[i] == 0)
            sub(i);

    if (error) {

        fout << "-1";
        return 0;
    }

    for (int i = -n; i < 0; i++)
        v[ctc[i]].push_back(i);
    for (int i = 1; i <= n; i++)
        v[ctc[i]].push_back(i), res[i] = -1;

    for (int i = nrCtc; i >= 1; i--) {

        for (auto &j : v[i]) {

            int aux = j;
            if (aux < 0)
                aux *= -1;

            if (res[aux] != -1)
                continue;

            if (j > 0)
                res[aux] = 0;
            else
                res[aux] = 1;
        }
    }

    for (int i = 1; i <= n; i++)
        fout << res[i] << ' ';

    return 0;
}