Cod sursa(job #2655558)

Utilizator isa_tudor_andreiAndrei Tudor isa_tudor_andrei Data 4 octombrie 2020 18:01:17
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 100000;
//1->1 -1->N+1
vector<int> G[2*NMAX + 1], Gt[2*NMAX + 1], st;
int n, m, comp[2*NMAX + 1], viz[2*NMAX + 1], ans[NMAX + 1];

int Not( int x ) {
  if( x > 0 )
    return n + x;
  return -x;
}

int Norm( int x ) {
  if( x < 0 )
    return n - x;
  return x;
}

void add( int x, int y ) {
  G[x].push_back(y);
  Gt[y].push_back(x);
}

void dfs1( int node ) {
  viz[node] = true;
  for( const auto &it : G[node] )
    if( viz[it] == false )
      dfs1(it);
  st.push_back(node);
}

void dfs2( int node, int c ) {
  comp[node] = c;
  for( const auto &it : Gt[node] )
    if( comp[it] == 0 )
      dfs2(it, c);
}

int main() {
    fin>>n>>m;
    for( int i = 1; i <= m; i ++ ) {
      int x, y;
      fin>>x>>y;
      add(Not(x), Norm(y));
      add(Not(y), Norm(x));
    }

    for( int i = 1; i <= 2 * n; i ++ ) {
      if( viz[i] == 0 )
        dfs1(i);
    }

    int c = 0;
    for( int i = 1; i <= 2 * n; i ++ ) {
      int node = st[2 * n - i];
      if( comp[node] == 0 )
        dfs2(node, ++ c);
    }

    for( int i = 1; i <= n; i ++ ) {
      if( comp[i] == comp[i + n] ) {
        fout<<"-1";
        return 0;
      }
      ans[i] = comp[i] > comp[i + n];
    }

    for( int i = 1; i <= n; i ++ )
      fout<<ans[i]<<" ";
    return 0;
}