Cod sursa(job #2943961)

Utilizator andrei_marciucMarciuc Andrei andrei_marciuc Data 21 noiembrie 2022 21:16:31
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <vector>

std::ifstream cin( "2sat.in" );
std::ofstream cout( "2sat.out" );

const int MAX = 1e5 + 6;

std::vector<int> rNoduri[ 2 * MAX ];
std::vector<int> noduri[ 2 * MAX ];
std::vector<int> ordine;
int *comp, nrctc;
bool *viz, ok;
int n, m;

int noot( int x ) {
    if( x > n )
        return x - n;
    else return x + n;
}

void dfs1( int u ) {
    viz[ u ] = 1;
    for( int v : noduri[ u ] )
        if( !viz[ v ] )
            dfs1( v );
    ordine.push_back( u );
}

void dfs2( int u ) {
    viz[ u ] = 0;
    comp[ u ] = nrctc;
    for( int v : rNoduri[ u ] )
        if( viz[ v ] )
            dfs2( v );
}

int main()
{
    /*read*/{
        int x, y;
        cin >> n >> m;

        /*make vectors*/{
            comp = new int[ 2 * n + 1 ]();
            viz = new bool[ 2 * n + 1 ]();
        }

        for( int i = 1; i <= m; i++ ) {
            cin >> x >> y;
            if( x < 0 )
                x = -x + n;
            if( y < 0 )
                y = -y + n;
            noduri[ noot( x ) ].push_back( y );
            noduri[ noot( y ) ].push_back( x );
            rNoduri[ x ].push_back( noot( y ) );
            rNoduri[ y ].push_back( noot( x ) );
        }
    }

    /*make ctc */{
        for( int i = 1; i <= 2 * n; i++ )
            if( !viz[ i ] )
                dfs1( i );

        for( auto elem = ordine.rbegin(); elem != ordine.rend(); elem++ )
            if( viz[ *elem ] ) {
                nrctc++;
                dfs2( *elem );
            }
    }

    /*solve*/{
        ok = 1;
        for( int i = 1; i <= n && ok; i++ )
            if( comp[ i ] == comp[ i + n ] )
                ok = 0;
    }

    /*afisare*/{
        if( ok )
            for( int i = 1; i <= n; i++ )
                cout << ( comp[ i ] > comp[ n + i ] ) << ' ';
        else cout << "-1\n";
    }

    return 0;
}