Cod sursa(job #2724765)

Utilizator rapidu36Victor Manz rapidu36 Data 17 martie 2021 19:43:04
Problema 2SAT Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <fstream>
#include <vector>
#include <cstdlib>
#include <stack>

using namespace std;

const int N = 1e5;

vector <int> aux[2*N+1], aux_t[2*N+1];
vector <int> *a, *a_t;
int n;
bool aux_viz[2*N+1], aux_viz_t[2*N+1], aux_val[2*N+1], aux_completat[2*N+1];
bool *viz, *viz_t, *val, *completat;
stack <int> stiva;

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

void dfs(int x)
{
    viz[x] = true;
    for (auto y : a[x])
    {
        if (!viz[y])
        {
            dfs(y);
        }
    }
    stiva.push(x);
}

void dfs_t(int x)
{
    viz_t[x] = true;
    if (!completat[x])
    {
        completat[x] = true;
        val[x] = false;
        completat[-x] = true;
        val[-x] = true;
    }
    else
    {
        if (val[x])
        {
            out << -1;
            out.close();
            exit(0);
        }
    }
    for (auto y: a_t[x])
    {
        if (!viz_t[y])
        {
            dfs_t(y);
        }
    }
}

int main()
{
    int m;
    in >> n >> m;
    a = aux + N;
    a_t = aux_t + N;
    viz = aux_viz + N;
    viz_t = aux_viz_t + N;
    val = aux_val + N;
    completat = aux_completat + N;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        a[-x].push_back(y);
        a_t[y].push_back(-x);
        a[-y].push_back(x);
        a_t[x].push_back(-y);
    }
    in.close();
    for (int i = -n; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs(i);
        }
    }
    while (!stiva.empty())
    {
        int x = stiva.top();
        stiva.pop();
        if (completat[x])
        {
            break;
        }
        if (!viz_t[x])
        {
            dfs_t(x);
        }
    }
    for (int i = 1; i <= n; i++)
    {
        out << val[i] << " ";
    }
    out.close();
    return 0;
}