Cod sursa(job #1243772)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 16 octombrie 2014 13:26:37
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>

using namespace std;

const int Nmax = 2e5 + 1;

vector <int> G[Nmax], GT[Nmax];
int postoder[Nmax], vis[Nmax], ans[Nmax];

int N, M, P, solution = 1;

int neg( int x )
{
    if ( x > N )
        return x - N;
    else
        return x + N;
}

void DFS( int nod )
{
    vis[nod] = 1;

    for ( auto x: G[nod] )
        if ( !vis[x] )
            DFS( x );

    postoder[ ++P ] = nod;
}

void DFST( int nod )
{
    if ( ans[nod] )
        solution = 0;

    vis[nod] = 0;
    ans[ neg( nod ) ] = 1;

    for ( auto x: GT[nod] )
        if ( vis[x] )
            DFST( x );
}

void SAT()
{
    for ( int i = 1; i <= 2 * N; ++i )
        if ( !vis[i] )
            DFS( i );

    for ( int i = P; i >= 1; i-- )
    {
        int nod = postoder[i];

        if ( vis[nod] && vis[ neg( nod ) ] )
            DFST( nod );
    }
}

int main()
{
    ifstream in("2sat.in");
    ofstream out("2sat.out");

    in >> N >> M;

    for ( int i = 1, x, y; i <= M; ++i )
    {
        in >> x >> y;

        if ( x < 0 ) x = -x + N;
        if ( y < 0 ) y = -y + N;

        G[ neg( x ) ].push_back( y );
        G[ neg( y ) ].push_back( x );

        GT[y].push_back( neg( x ) );
        GT[x].push_back( neg( y ) );
    }

    SAT();

    if ( solution )
    {
        for ( int i = 1; i <= N; ++i )
            out << ans[i] << " ";
    }
    else
        out << "-1\n";

    return 0;
}