Cod sursa(job #3361903)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 29 iulie 2026 19:00:16
Problema 2SAT Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 2e5 + 5;

int n, m, fr[nmax], ap[nmax];

vector <int> g[nmax], gt[nmax], scc[nmax];

stack <int> st;

int negNode (int x)
{
    return x <= n ? x + n : x - n;
}

void dfs (int node)
{
    fr[node] = 1;
    for (auto it : g[node])
    {
        if (!fr[it])
            dfs (it);
    }
    st.push (node);
}

void dfst (int node, int k)
{
    scc[k].push_back (node);
    fr[node] = 0;
    for (auto it : gt[node])
    {
        if (fr[it])
            dfst (it, k);
    }
}

void kosaraju ()
{
    int cnt = 0;
    for (int i = 1; i <= 2 * n; i++)
    {
        if (!fr[i])
            dfs (i);
    }
    while (!st.empty ())
    {
        int x = st.top ();
        st.pop ();
        if (fr[x])
        {
            cnt++;
            dfst (x, cnt);
        }
    }
    for (int i = 1; i <= cnt; i++)
    {
        for (auto it : scc[i])
        {
            ap[it] = i;
            if (ap[negNode (it)] == i)
            {
                fout << -1;
                return;
            }
        }
    }
    for (int i = 1; i <= n; i++)
        fout << (ap[i] < ap[i + n] ? 1 : 0) << " ";
}

signed main ()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        x = (x > 0) ? x : -x + n;
        y = (y > 0) ? y : -y + n;
        g[negNode (x)].push_back (y);
        gt[y].push_back (negNode (x));
        g[negNode (y)].push_back (x);
        gt[x].push_back (negNode (y));
    }
    kosaraju ();
    return 0;
}