Cod sursa(job #2466570)

Utilizator LeVladzCiuperceanu Vlad LeVladz Data 2 octombrie 2019 17:21:43
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <fstream>
#include <vector>
#include <stack>
#include <set>
#define DIM 200005

using namespace std;

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

int n,m,i,j,x,y,ind,cnt,v[DIM],sol[DIM],low[DIM];
bool fs[DIM],ok;
vector<int> L[DIM],ctc[DIM];
stack<int> s;
set<int> w;

void dfs(int nod)
{
    ind++; v[nod] = ind; s.push(nod);
    low[nod] = ind; fs[nod] = true;
    for (int i=0; i<L[nod].size(); i++)
    {
        int vecin = L[nod][i];
        if (!v[vecin])
        {
            dfs(vecin);
            low[nod] = min(low[nod], low[vecin]);
        }
        else
            if (fs[vecin])
                low[nod] = min(low[nod], v[vecin]);
    }
    if (v[nod] == low[nod])
    {
        int vecin = 0; cnt++; w.clear();
        do {
            vecin = s.top(); s.pop(); w.insert(vecin);
            fs[vecin] = false; ctc[cnt].push_back(vecin);
            if ((vecin <= n && w.find(vecin+n) != w.end()) || (vecin > n && w.find(vecin-n) != w.end()))
                ok = true;
            if (sol[vecin] == 0)
            {
                sol[vecin] = 1;
                if (vecin <= n)
                    sol[vecin+n] = -1;
                else
                    sol[vecin-n] = -1;
            }
        } while (nod != vecin);
    }
}

int main()
{
    fin >> n >> m;
    for (i=1; i<=m; i++)
    {
        fin >> x >> y;
        if (x > 0 && y > 0)
        {
            L[x+n].push_back(y);
            L[y+n].push_back(x);
        }
        if (x > 0 && y < 0)
        {
            L[x+n].push_back(-y+n);
            L[-y].push_back(x);
        }
        if (x < 0 && y > 0)
        {
            L[-x].push_back(y);
            L[y+n].push_back(-x+n);
        }
        if (x < 0 && y < 0)
        {
            L[-x].push_back(-y+n);
            L[-y].push_back(-x+n);
        }
    }
    for (i=1; i<=2*n; i++)
        if (!v[i])
            dfs(i);
    if (ok == true)
    {
        fout << -1;
        return 0;
    }
    for (i=1; i<=n; i++)
        if (sol[i] == -1)
            fout << 0 << " ";
        else
            fout << 1 << " ";
    return 0;
}