Cod sursa(job #1937032)

Utilizator robx12lnLinca Robert robx12ln Data 23 martie 2017 17:03:24
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.68 kb
#include<fstream>
#include<stack>
#include<vector>
#include<set>
#define DIM 200005
using namespace std;
ifstream fin("2sat.in");
ofstream fout("2sat.out");
int x, y, n, m, niv[DIM], low[DIM], nr, comp[DIM], f[DIM], cod, val[DIM], vf;
vector<int> v[DIM];
stack<int> st;
set<int> ok;
void dfs( int nod ){
    cod++;
    niv[nod] = low[nod] = cod;
    f[nod] = 1;
    st.push( nod );
    for( int i = 0; i < v[nod].size(); i++ ){
        int vecin = v[nod][i];
        if( niv[vecin] == 0 ){
            dfs( vecin );
            low[nod] = min( low[nod], low[vecin] );
        }else{
            if( f[vecin] == 1 ){
                low[nod] = min( low[nod], low[vecin] );
            }
        }
    }
    if( niv[nod] == low[nod] ){
        nr++;
        ok.clear();
        while( st.top() != nod ){
            int x = st.top();
            f[x] = 0;
            ok.insert(x);
            if( ( x <= n && ok.find( x + n ) != ok.end() ) || ( x > n && ok.find( x - n ) != ok.end() ) ){
                vf = -1;
            }
            if( val[x] == 0 ){
                val[x] = 1;
                if( x <= n ){
                    val[x + n] = -1;
                }else{
                    val[x - n] = -1;
                }
            }
            st.pop();
        }
        int x = st.top();
        f[x] = 0;
        ok.insert(x);
        if( ( x <= n && ok.find( x + n ) != ok.end() ) || ( x > n && ok.find( x - n ) != ok.end() ) ){
            vf = -1;
        }
        if( val[x] == 0 ){
            val[x] = 1;
            if( x <= n ){
                val[x + n] = -1;
            }else{
                val[x - n] = -1;
            }
        }
        st.pop();
    }
    return;
}
int main(){
    fin >> n >> m;
    for( int i = 1; i <= m; i++ ){
        fin >> x >> y;
        if( x > 0 ){
            if( y > 0 ){
                v[n + x].push_back( y );
                v[n + y].push_back( x );
            }else{
                v[n + x].push_back( n - y );
                v[-y].push_back( x );
            }
        }else{
            if( y > 0 ){
                v[-x].push_back( y );
                v[n + y].push_back( n - x );
            }else{
                v[-x].push_back( n - y );
                v[-y].push_back( n - x );
            }
        }
    }
    cod = 0;
    for( int i = 1; i <= n * 2; i++ ){
        if( niv[i] == 0 ){
            dfs( i );
        }
    }
    if( vf == -1 ){
        fout << "-1\n";
        return 0;
    }
    for( int i = 1; i <= n; i++ ){
        if( val[i] == 1 ){
            fout << "1 ";
        }else{
            fout << "0 ";
        }
    }
    return 0;
}