Cod sursa(job #1656296)

Utilizator rapidu36Victor Manz rapidu36 Data 19 martie 2016 07:34:43
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

const int N = 100000;
const int M = 400000;

ifstream in;
ofstream out;

int auxlst[2][2*N+1], *lst[2], c[2*N+1], n, nc;
bool auxr[2*N+1], *r, auxviz[2*N+1], *viz;
int vf[2][2*M+1], urm[2][2*M+1], nr[2];

inline void adauga(int x, int y, int tip)
{
    nr[tip]++;
    vf[tip][nr[tip]] = y;
    urm[tip][nr[tip]] = lst[tip][x];
    lst[tip][x] = nr[tip];
}

void citire()
{
    int i, x, y, m;
    in.open("2sat.in");
    lst[0] = auxlst[0] + N;
    lst[1] = auxlst[1] + N;
    r = auxr + N;
    viz = auxviz + N;
    in >> n >> m;
    for (i = 0; i < m; i++)
    {
        in >> x >> y;
        adauga(-x, y, 0);
        adauga(y, -x, 1);
        adauga(-y, x, 0);
        adauga(x, -y, 1);
    }
    in.close();
}

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

void dfs1(int x)
{
    int p, y;
    viz[x] = true;
    r[-x] = true;
    p = lst[1][x];
    while (p != 0)
    {
        y = vf[1][p];
        if (!viz[y])
            dfs1(y);
        p = urm[1][p];
    }
}

void tareconexe()
{
    int i;
    for (i = -n; i <= n; i++)
        if (i != 0 && !viz[i])
            dfs0(i);
    memset(auxviz, 0, (2 * N + 1) * sizeof(bool));
    for (i = nc; i >= 1; i--)
        if (!viz[c[i]] && !viz[-c[i]])
            dfs1(c[i]);
}

void scrie()
{
    out.open("2sat.out");
    int i;
    for (i = 1; i <= n; i++)
        if (r[i] == r[-i])
        {
            out << "-1\n";
            out.close();
            return;
        }
    for (i = 1; i < n; i++)
        out << (int)r[i] << " ";
    out << (int)r[n] << "\n";
    out.close();
}

int main()
{
    citire();
    tareconexe();
    scrie();
    return 0;
}