Cod sursa(job #2510016)

Utilizator robx12lnLinca Robert robx12ln Data 15 decembrie 2019 16:39:13
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include<bits/stdc++.h>
using namespace std;

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

const int DIM = 2e5 + 5;
int N, M, cod, niv[DIM], low[DIM], f[DIM], ans[DIM];
bool ok = true;
stack<int> st;
vector<int> edge[DIM];
set<int> S;

inline int convert( int x ){
    if( x < 0 )
        return -x;
    return x + N;
}

inline int inv( int a ){
    if( a <= N )
        return a + N;
    return a - N;
}

void dfs( int nod ){
    st.push( nod );
    f[nod] = 1;
    niv[nod] = low[nod] = ++cod;
    for( int i = 0; i < edge[nod].size(); i++ ){
        int v = edge[nod][i];
        if( niv[v] == 0 ){
            dfs( v );
            low[nod] = min( low[nod], low[v] );
        }else{
            if( f[v] == 1 )
                low[nod] = min( low[nod], low[v] );
        }
    }

    if( low[nod] == niv[nod] ){
        S.clear();
        while( st.top() != nod ){
            if( S.find( inv(st.top()) ) != S.end() )
                ok = false;
            if( ans[ st.top() ] == -1 ){
                ans[ st.top() ] = 1;
                ans[ inv( st.top() ) ] = 0;
            }
            S.insert( st.top() );
            f[ st.top() ] = 0;
            st.pop();
        }
        if( S.find( inv(st.top()) ) != S.end() )
            ok = false;
        if( ans[ st.top() ] == -1 ){
            ans[ st.top() ] = 1;
            ans[ inv( st.top() ) ] = 0;
        }
        S.insert( st.top() );
        f[ st.top() ] = 0;
        st.pop();
    }

}

int main(){
    fin >> N >> M;
    for( int i = 1; i <= M; i++ ){
        int a, b; fin >> a >> b;
        a = convert( a );
        b = convert( b );
        edge[inv(a)].push_back( b );
        edge[inv(b)].push_back( a );
    }
    memset( ans, -1, sizeof(ans) );
    for( int i = 1; i <= N; i++ ){
        if( niv[i] == 0 )
            dfs( i );
    }

    if( ok == false )
        fout << "-1\n";
    else{
        for( int i = N + 1; i <= N + N; i++ )
            fout << ans[i] << " ";
    }
    return 0;
}