Cod sursa(job #3251753)

Utilizator Alex_BerbescuBerbescu Alexandru Alex_Berbescu Data 26 octombrie 2024 19:20:56
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <bits/stdc++.h>
using namespace std;

const int dim = 2e5 + 55;
int n, m, x[dim], y[dim], counter, conex[dim + 55];
bool sol[dim], ok = true;
vector<int> noduri[dim + 55], nodurigt[dim + 55];
bitset<2 * dim> viz;
stack<int> stiva;

void dfs(int nod)
{
    viz[nod] = 1;
    for (auto it : noduri[nod])
    {
        if (!viz[it])
        {
            dfs(it);
        }
    }
    stiva.push(nod);
}
int neg(int valu)
{
    if(valu > n)
    {
        valu -= n;
    }
    else
    {
        valu += n;
    }
    return valu;
}
void dfsdoi(int nod)
{
    viz[nod] = 1;
    conex[nod] = counter;
    for (auto it : nodurigt[nod])
    {
        if (!viz[it])
        {
            dfsdoi(it);
        }
    }
}

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

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        fin >> x[i] >> y[i];
        if(x[i] < 0)
        {
            x[i] = n - x[i];
        }
        if(y[i] < 0)
        {
            y[i] = n - y[i];
        }
        noduri[neg(x[i])].push_back(y[i]);
        noduri[neg(y[i])].push_back(x[i]);
        nodurigt[x[i]].push_back(neg(y[i]));
        nodurigt[y[i]].push_back(neg(x[i]));
    }

    for (int i = 1; i <= 2 * n; ++i)
    {
        if (!viz[i]) dfs(i);
    }

    viz.reset();
    while (!stiva.empty())
    {
        int val = stiva.top();
        stiva.pop();
        if (!viz[val])
        {
            counter++;
            dfsdoi(val);
        }
    }
    for(int i = 1; i <= n; ++i)
    {
        if(conex[i] == conex[i + n])
        {
            ok = 0;
            break;
        }
        else
        {
            if(conex[i] > conex[i + n])
            {
                sol[i] = 1;
            }
        }
    }
    if(ok == 1)
    {
        for(int i = 1; i <= n; ++i)
        {
            fout << sol[i] << " ";
        }
    }
    else
    {
        fout << -1;
    }

    return 0;
}