Cod sursa(job #1067287)

Utilizator romircea2010FMI Trifan Mircea Mihai romircea2010 Data 26 decembrie 2013 17:36:55
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>
#include <vector>
#define NMax 100010
#define MMax 200010

using namespace std;

bool ans[2*NMax];
int n21;
vector <int> G[2*NMax], GT[2*NMax];
int n, m;
int postordine[2*NMax], npostordine;
bool viz[2*NMax];
bool existaSol;

inline int neg(const int &x)
{
    return n21-x;
}

void Read()
{
    ifstream f ("2sat.in");
    f>>n>>m;
    n21 = n+n+1;
    for (int i = 1; i<=m; ++i)
    {
        int x, y;
        f>>x>>y;
        if (x < 0)
            x = neg(-x);
        if (y < 0)
            y = neg(-y);
        G[neg(x)].push_back(y);
        G[neg(y)].push_back(x);
        GT[y].push_back(neg(x));
        GT[x].push_back(neg(y));
    }
    f.close();
}

inline void DFS(const int node)
{
    viz[node] = true;
    for (vector <int>::iterator it = G[node].begin(); it!=G[node].end(); ++it)
        if (!viz[*it])
            DFS(*it);
    postordine[++npostordine] = node;
}

inline void DFST(const int node)
{
    if (ans[node])
    {
        existaSol = false;
        return;
    }
    ans [neg(node)] = true;
    viz[node] = false;
    for (vector <int>::iterator it = GT[node].begin(); it!=GT[node].end(); ++it)
        if (viz[*it])
            DFST(*it);
}

void Solve()
{
    existaSol = true;
    int i;
    for (i=1; i < n21; ++i)
        if (!viz[i])
            DFS(i);
    for (i = n21 - 1; i; --i)
        if (viz[postordine[i]] && viz[neg(postordine[i])])
            DFST(postordine[i]);
}

void Write()
{
    ofstream g("2sat.out");
    if (!existaSol)
        g<<"-1";
    else
        for (int i=1; i<=n; ++i)
            if (ans[i])
                g<<"1 ";
            else
                g<<"0 ";
    g<<"\n";
    g.close();

}

int main()
{
    Read();
    Solve();
    Write();
    return 0;
}