Cod sursa(job #1651948)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 14 martie 2016 11:51:14
Problema 2SAT Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include<fstream>
#include<vector>
#include<cstring>

using namespace std;

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

typedef vector< int > graf;

const int nmax = 1e5;
int n, m;
int c[ 2 * nmax + 1 ];
bool viz[ 2 * nmax + 1 ];
graf g[ 2 * nmax + 1 ][ 2 ];

vector< int > ord;

inline int cod( int x ) {
    if ( x < 0 ) {
        return -x;
    }
    return x + n;
}
inline int neg( int x ) {
    if ( x <= n ) {
        return x + n;
    }
    return x - n;
}
void dfs( int nod, int ind ) {
    viz[ nod ] = 1;

    for( graf::iterator it = g[ nod ][ ind ].begin(); it != g[ nod ][ ind ].end(); ++ it ) {
        if ( viz[ *it ] == 0 ) {
            dfs( *it, ind );
        }
    }

    if ( ind == 0 ) {
        ord.push_back( nod );
    } else {
        c[ nod ] = m;
    }
}
void comp_conexe() {
    for( int i = 1; i <= 2 * n; ++ i ) {
        if ( viz[ i ] == 0 ) {
            dfs( i, 0 );
        }
    }

    memset( viz, 0, sizeof( viz ) );
    m = 0;
    for( int i = ord.size() - 1; i >= 0; -- i ) {
        if ( viz[ ord[ i ] ] == 0 ) {
            ++ m;
            dfs( ord[ i ], 1 );
        }
    }
}

int main() {
    int m;
    fin >> n >> m;
    for( int i = 1; i <= m; ++ i ) {
        int x, y;
        fin >> x >> y;
        x = cod( x ); y = cod( y );
        g[ neg( x ) ][ 0 ].push_back( y );
        g[ neg( y ) ][ 0 ].push_back( x );

        g[ x ][ 1 ].push_back( neg( y ) );
        g[ y ][ 1 ].push_back( neg( x ) );
    }

    comp_conexe();
    bool ok = 1;
    for( int i = 1; i <= n; ++ i ) {
        if ( c[ i ] == c[ neg( i ) ] ) {
            ok = 0;
        }
    }

    if ( ok == 1 ) {
        for( int i = n + 1; i <= 2 * n; ++ i ) {
            if ( c[ i ] <= m / 2 ) {
                fout << "0 ";
            } else {
                fout << "1 ";
            }
        }
    } else {
        fout << "-1";
    }
    fout << "\n";
    fin.close();
    fout.close();
    return 0;
}