Cod sursa(job #2974195)

Utilizator rapidu36Victor Manz rapidu36 Data 3 februarie 2023 15:34:28
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.17 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>

using namespace std;

const int N = 1e5;

vector <int> succesori[N+N+1];
vector <int> predecesori[N+N+1];
vector <int> ordine;
bitset <N+N+1> viz;
bitset <N+1> val;
int ctc[N+N+1], nctc;

int val_asoc(int x)
{
    if (x < 0)
    {
        return -2 * x - 1;
    }
    return 2 * x;
}

int negatie(int x)
{
    if (x % 2 == 0)
    {
        return x - 1;
    }
    return x + 1;
}

void dfs_init(int x)
{
    viz[x] = 1;
    for (auto y: succesori[x])
    {
        if (!viz[y])
        {
            dfs_init(y);
        }
    }
    ordine.push_back(x);
}

void dfs_transpus(int x)
{
    ctc[x] = nctc;
    for (auto y: predecesori[x])
    {
        if (ctc[y] == 0)
        {
            dfs_transpus(y);
        }
    }
}

int main()
{
    ifstream in("2sat.in");
    ofstream out("2sat.out");
    int n, m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        x = val_asoc(x);
        y = val_asoc(y);
        succesori[negatie(x)].push_back(y);///muchie de la !x la y
        predecesori[y].push_back(negatie(x));
        swap(x, y);
        succesori[negatie(x)].push_back(y);///muchie de la !x la y
        predecesori[y].push_back(negatie(x));
    }
    for (int i = 1; i <= 2 * n; i++)
    {
        if (!viz[i])
        {
            dfs_init(i);
        }
    }
    reverse(ordine.begin(), ordine.end());
    for (auto x: ordine)
    {
        if (ctc[x] == 0)
        {
            ++nctc;
            dfs_transpus(x);
        }
    }
    bool este_sat = true;
    for (int i = 1; i <= 2 * n; i += 2)
    {
        if (ctc[i] < ctc[i+1])
        {
            val[(i + 1) / 2] = 1;
        }
        else if (ctc[i+1] < ctc[i])
        {
            val[(i + 1) / 2] = 0;
        }
        else
        {
            este_sat = false;
        }
    }
    if (!este_sat)
    {
        out << -1;
    }
    else
    {
        for (int i = 1; i <= n; i++)
        {
            out << val[i] << " ";
        }
    }
    in.close();
    out.close();
    return 0;
}