Cod sursa(job #2638390)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 28 iulie 2020 08:43:07
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int NMAX = 2e5;

int N, M;
vector <int> g[NMAX + 2];
vector <int> r[NMAX + 2];

int Nrm(int x)
{
    if(x < 0)
        return -x + N;

    return x;
}

int Not(int x)
{
    if(x < 0)
        return -x;

    return x + N;
}

stack <int> st;
bool d[NMAX + 2];

void dfs1(int node)
{
    d[node] = true;

    for(auto it : g[node])
        if(!d[it])
            dfs1(it);

    st.push(node);
}

int nrc;
int comp[NMAX + 2];

void dfs2(int node)
{
    d[node] = 1;
    comp[node] = nrc;

    for(auto it : r[node])
        if(!d[it])
            dfs2(it);
}

int main()
{
    cin >> N >> M;

    for(int i = 1; i <= M; i++)
    {
        int x, y;
        cin >> x >> y;

        g[Not(x)].push_back(Nrm(y));
        g[Not(y)].push_back(Nrm(x));

        r[Nrm(y)].push_back(Not(x));
        r[Nrm(x)].push_back(Not(y));
    }

    for(int i = 1; i <= 2 * N; i++)
        if(!d[i])
            dfs1(i);

    for(int i = 1; i <= 2 * N; i++)
        d[i] = 0;

    while(!st.empty())
    {
        int node = st.top();
        st.pop();

        if(!d[node])
            {
                ++nrc;
                dfs2(node);
            }
    }

    vector <bool> sol;
    for(int i = 1; i <= N; i++)
        if(comp[i] == comp[i + N])
            {
                cout << -1 << '\n';
                return 0;
            }
        else
            sol.push_back((comp[i] > comp[i + N]));

    for(auto it : sol)
        cout << it << ' ';

    return 0;
}