Cod sursa(job #2798714)

Utilizator MenelausSontea Vladimir Menelaus Data 11 noiembrie 2021 19:23:08
Problema 2SAT Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

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

const int N=100000;

std::vector<int> v[2*N+1];
std::vector<int> t[2*N+1];
int ctc[2*N+1];

int n, m;

int non(int x)
{
    return x-(x>=N+1)*N;
}

bool srt[2*N+1];
std::stack<int> q;
void sort_top(int i)
{
    srt[i]=true;

    for(int copil : v[i])
    {
        if(!srt[copil])
        {
            sort_top(copil);
        }
    }

    q.push(i);
}

void Kosaraju(int i, int nr)
{
    for(int copil : t[i])
    {
        if(!ctc[copil])
        {
            Kosaraju(copil, nr);
        }
    }

    ctc[i]=nr;
}

int main()
{
    int x, y;

    in>>n>>m;
    for(int i=1; i<=m; i++)
    {
        in>>x>>y;
        if(x<0)
        {
            x=(-x)+N;
        }
        if(y<0)
        {
            y=(-y)+N;
        }

        v[non(x)].push_back(y);
        v[non(y)].push_back(x);

        t[y].push_back(not(x));
        t[x].push_back(not(y));
    }

    /// sortare top
    for(int i=1; i<=2*N; i++)
    {
        if(!srt[i])
        {
            sort_top(i);
        }
    }

    /// Kosaraju
    int nr=0;
    while(!q.empty())
    {
        if(!ctc[q.top()])
        {
            Kosaraju(q.top(), ++nr);
        }

        q.pop();
    }

    for(int i=1; i<=n; i++)
    {
        if(ctc[i]==ctc[i+N])
        {
            out<<-1;
            return 0;
        }
    }

    for(int i=1; i<=n; i++)
    {
        out<<(ctc[i]<ctc[i+N])<<" ";
    }
}