Cod sursa(job #1463223)

Utilizator petru.cehanCehan Petru petru.cehan Data 20 iulie 2015 16:03:32
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <cstring>
#include <fstream>
#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

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

int N , M ;
vector < int > Graph[200002];

int E1[200002] , E2[200002] ;
int stiva [200002] , top_s ;
bool viz[200002] , val[200002] ;
bool done[200002] ;

int op ( int x )
{
    return ( x <= N ? x + N : x - N ) ;
}

void DFS ( int nd )
{
    viz[nd] = true;
    for ( unsigned int i = 0 ; i < Graph[nd].size() ; ++ i )
        if ( viz [ Graph[nd][i] ] == 0 )
            DFS ( Graph[nd][i] ) ;

    stiva[ ++ top_s ] = nd ;
}

int main()
{
    fin >> N >> M;
    for ( int i = 1 , nod1 , nod2 ; i <= M ; ++ i )
    {
        fin >> nod1 >> nod2;
        if ( nod1 < 0 ) nod1 = N - nod1 ; // daca e negat , N + | nod |
        if ( nod2 < 0 ) nod2 = N - nod2 ;

        E1[i] = nod1;
        E2[i] = nod2;

        Graph[op(nod1)].push_back(nod2);
        Graph[op(nod2)].push_back(nod1);
    }

    for ( int i = 1 ; i <= 2 * N ; ++ i )
        if ( !viz[i] )
            DFS (i) ;

    for ( int i = top_s ; i >= 1 ; -- i )
        if ( done[ op( stiva[i] ) ] == false )
            done[ stiva[i] ] = true;
        else
            val[ stiva[i]] = !val[ op( stiva[i] )];

    bool ok = true;
    for ( int i = 1 ; i <= M; ++ i )
        if ( val[ E1[i] ] == false && val[ E2[i] ]== false )
            {
                ok = false ; break ;
            }

    if ( ok == false )
        fout << -1 << '\n';
    else
    {
        for ( int i = 1 ; i <= N ; ++ i )
            fout << val[i] << ' ';
        fout << '\n';
    }

    fin.close();
    fout.close();

    for ( int i = 1 ; i <= 2 * N ; ++ i )
        cout << stiva [i] << " " ;

    return 0 ;
}