Cod sursa(job #1741164)

Utilizator StarGold2Emanuel Nrx StarGold2 Data 13 august 2016 02:51:02
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
using namespace std;

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

const int DIM = 2e5 + 5;
const int INF = 0x3f3f3f3f;

int N, M, X, Y, ok = 1, cnt;
int Lev[DIM], Low[DIM], Sol[DIM];
set <int> Set; vector<int> G[DIM]; stack <int> St;

void dfs( int node ) {
    Low[node] = Lev[node] = ++cnt;
    St.push( node );

    for( auto it : G[node] ) {
        if( Lev[it] == 0 )
            dfs( it );

        if( Lev[it] > 0 )
            Low[node] = min( Low[node], Low[it] );
    }

    if( Low[node] == Lev[node] ) {
        int aux;
        Set.clear();

        do {
            aux = St.top(); Lev[aux] *= -1;
            St.pop(); Set.insert( aux );

            if( aux <= N && Set.find( aux + N ) != Set.end() )
                ok = 0;

            if( aux >  N && Set.find( aux - N ) != Set.end() )
                ok = 0;

            if( Sol[aux] == 0 ) {
                Sol[aux] = 1;

                if( aux <= N )
                    Sol[aux + N] = -1;
                else
                    Sol[aux - N] = -1;
            }

        } while( aux != node );
    }

    return;
}

inline int f( int X ) {
    return (X > 0) ? X : (-X + N);
}

int main( int argc, const char *argv[] ) {

    in >> N >> M;
    for( int i = 1; i <= M; i ++ ) {
        in >> X >> Y;
        G[ f(-X) ].push_back( f(Y) );
        G[ f(-Y) ].push_back( f(X) );
    }

    for( int i = 1; i <= N; i ++ ) {
        if( Lev[i] == 0 )
            dfs( i );
    }

    if( ok == 0 )
        out << -1;
    else {
        for( int i = 1; i <= N; i ++ )
            out << ( Sol[i] > 0 ) << " ";
        out << '\n';
    }

    return 0;
}