Cod sursa(job #1434691)

Utilizator rumburakrumburak rumburak Data 11 mai 2015 09:33:57
Problema 2SAT Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <iostream>
#include <fstream>

using namespace std;

const int N = 100001, M = 400001;

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

int auxlst[2*N], auxlst2[2*N], vf[2*M], vf2[2*M], urm[2*M], urm2[2*M], auxc[2*N], ord[2*N], r[N], varf[N];
int *lst, *lst2, *c, nr, nr2, n, m, cc;
bool viz[2*N], viz2[2*N];

void init()
{
    lst = auxlst + N;
    lst2 = auxlst2 + N;
    c = auxc + N;
}

void adauga1(int x, int y)
{
    //adauga muchie in graful initial
    nr++;
    vf[nr] = y;
    urm[nr] = lst[x];
    lst[x] = nr;
}

void adauga2(int x, int y)
{
    //adauga muchie in graful transpus
    nr2++;
    vf2[nr2] = y;
    urm2[nr2] = lst2[x];
    lst2[x] = nr2;
}

void adauga(int x, int y)
{
    //adauga o relatie de forma x sau y, adica -x -> y si -y -> x
    adauga1(-x, y);
    adauga2(y, -x);

    adauga1(-y, x);
    adauga2(x, -y);
}

void dfs(int x)
{
    viz[x] = true;
    int p = lst[x], y;
    while (p != 0)
    {
        y = vf[p];
        if (!viz[y])
            dfs(y);
        p = urm[p];
    }
    ord[++nr] = x;
}

void dfs2(int x)
{
    viz2[x] = true;
    c[x] = cc;
    int p = lst2[x], y;
    while (p != 0)
    {
        y = vf2[p];
        if (!viz2[y])
            dfs2(y);
        p = urm2[p];
    }
}

int main()
{
    int x, y, i;
    init();
    in >> n;
    in >> m;
    //m = n;
    for (i = 1; i <= m; i++)
    {
        in >> x >> y;
        adauga(x, y);
    }
    in.close();
    nr = 0;
    for (i = -n; i <= n; i++)
        if (i != 0 and !viz[i])
        {
            dfs(i);
        }
    for (i = 2*n; i > 0; i--)
        if (!viz2[ord[i]])
        {
            cc++;
            varf[cc] = ord[i];
            dfs2(ord[i]);
        }
    for (i = 1; i <= n; i++)
    {
        if (c[i] == c[-i])
        {
            out << "-1\n";
            out.close();
            return 0;
        }
    }
    for (i = 1; i <= cc; i++)
        if (r[i] == 0)
        {
            r[i] = 1;
            r[c[-varf[i]]] = 2;
        }
    for (i = 1; i <= n; i++)
        out << r[c[i]] - 1 << " ";
    return 0;
}