Cod sursa(job #3345287)

Utilizator CheeseEaterHackRoman Alex CheeseEaterHack Data 8 martie 2026 22:01:05
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("2sat.in");
ofstream fout("2sat.out");

int n, m, a, b, disc[200001], low[200001], comp[200001], ok;
vector<int> graf[200001];
stack<int> st;
bool inStack[200001];
int timer, cnt, anrm, bnrm, aneg, bneg;

void dfs(int nod)
{
    timer++;
    disc[nod]=low[nod]=timer;
    st.push(nod);
    inStack[nod]=true;
    for (auto u: graf[nod])
    {
        if (disc[u]==0)
        {
            dfs(u);
            low[nod]=min(low[nod], low[u]);
        }
        else if (inStack[u])
        {
            low[nod]=min(low[nod], disc[u]);
        }
    }
    if (low[nod]==disc[nod])//am gasit un SCC cu radacina in nod
    {
        cnt++;
        while (true)
        {
            int nd=st.top();
            st.pop();
            inStack[nd]=false;
            comp[nd]=cnt;
            if (nd<=n and comp[nd+n]==comp[nd])
            {
                ok=1;
            }
            else if (nd>n and comp[nd-n]==comp[nd])
            {
                ok=1;
            }
            if (nd==nod)
            {
                break;
            }
        }
    }
}


int main()
{
    fin>>n>>m;
    for (int i=1; i<=m; i++)
    {
        fin>>a>>b;
        if (a<0)
        {
            anrm=-a+n;
            aneg=-a;
        }
        else
        {
            anrm=a;
            aneg=a+n;
        }
        if (b<0)
        {
            bnrm=-b+n;
            bneg=-b;
        }
        else
        {
            bnrm=b;
            bneg=b+n;
        }
        graf[aneg].push_back(bnrm);
        graf[bneg].push_back(anrm);
    }
    for (int i=1; i<=2*n; i++)
    {
        if (disc[i]==0)
        {
            dfs(i);
        }
    }
    if (ok==1)
    {
        fout<<-1<<'\n';
        return 0;
    }
    else
    {
        for (int i=1; i<=n; i++)
        {
            fout<<(comp[i]<comp[i+n])<<" ";
        }
    }

    return 0;
}