Cod sursa(job #3142928)

Utilizator rapidu36Victor Manz rapidu36 Data 25 iulie 2023 22:51:34
Problema 2SAT Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

const int N = 1e5;

vector <int> s[2*N+1], p[2*N+1];
vector <int> t_i, t_f, sort_top, ctc;
int n, m, timp;

int varf(int val)
{
    if (val > 0)
    {
        return 2 * val;
    }
    return -2 * val - 1;
}

int negat(int vf)
{
    if (vf % 2 == 0)
    {
        vf--;
    }
    else
    {
        vf++;
    }
    return vf;
}

void dfs_sort_top(int x)
{
    t_i[x] = ++timp;
    for (auto y: s[x])
    {
        if (t_i[y] == 0)
        {
            dfs_sort_top(y);
        }
    }
    t_f[x] = ++timp;
    sort_top.push_back(x);
}

void dfs_ctc(int x, int nr_ctc)
{
    ctc[x] = nr_ctc;
    for (auto y: p[x])
    {
        if (ctc[y] == 0)
        {
            dfs_ctc(y, nr_ctc);
        }
    }
}

int main()
{
    ifstream in("2sat.in");
    ofstream out("2sat.out");
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        x = varf(x);
        y = varf(y);
        s[negat(x)].push_back(y);
        s[negat(y)].push_back(x);
    }
    ///Kosaraju:
    t_i.resize(2 * n + 1, 0);
    t_f.resize(2 * n + 1, 0);
    sort_top.reserve(2 * n + 1);
    timp = 0;
    for (int i = 1; i <= 2 * n; i++)
    {
        if (t_i[i] == 0)
        {
            dfs_sort_top(i);
        }
    }
    reverse(sort_top.begin(), sort_top.end());
    ctc.resize(2 * n + 1, 0);
    int nr_ctc = 0;
    for (auto x: sort_top)
    {
        if (ctc[x] == 0)
        {
            nr_ctc++;
            dfs_ctc(x, nr_ctc);
        }
    }
    vector <bool> sol(n + 1);
    bool exista_sol = true;
    for (int i = 1; i <= n; i++)
    {
        if (ctc[2 * i] == ctc[2 * i - 1])
        {
            exista_sol = false;
            break;
        }
        if (ctc[2 * i] < ctc[2 * i - 1])
        {
            sol[i] = 0;
        }
        else
        {
            sol[i] = 1;
        }
    }
    if (exista_sol)
    {
        for (int i = 1; i < n; i++)
        {
            out << sol[i] << " ";
        }
        out << sol[n] << "\n";
    }
    else
    {
        out << "-1\n";
    }
    in.close();
    out.close();
    return 0;
}