Cod sursa(job #1687393)

Utilizator depevladVlad Dumitru-Popescu depevlad Data 12 aprilie 2016 20:31:12
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <vector>
#include <cstdlib>
#include <algorithm>

#define pb push_back
#define neg(x) (x <= n ? x + n : x - n)

using namespace std;

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

const int N = 100005;

int n, m;
vector<int> g[2 * N], gt[2 * N], lst;
bool vis[2 * N], sol[2 * N];

void noSolution() {
   out << "-1\n";
   exit(0);
}

void firstPass(int x) {
   vis[x] = 1;
   for(auto y : g[x]) {
      if(!vis[y]) {
         firstPass(y);
      }
   }
   lst.pb(x);
}

void secondPass(int x) {
   if(sol[x] == 1) {
      noSolution();
   }
   vis[x] = 1;
   sol[neg(x)] = 1;
   for(auto y : gt[x]) {
      if(!vis[y]) {
         vis[y] = 1;
         secondPass(y);
      }
   }
}

int main() {
   int i, x, y;

   in >> n >> m;
   for(i = 1; i <= m; i++) {
      in >> x >> y;
      if(x < 0) x = neg(-x);
      if(y < 0) y = neg(-y);

      g[neg(x)].pb(y);
      g[neg(y)].pb(x);

      gt[y].pb(neg(x));
      gt[x].pb(neg(y));
   }

   for(i = 1; i <= 2*n; i++) {
      if(!vis[i]) {
         firstPass(i);
      }
   }

   fill(vis, vis + 2*N, 0);
   reverse(lst.begin(), lst.end());

   for(auto i : lst) {
      if(!vis[i] && !vis[neg(i)]) {
         secondPass(i);
      }
   }

   for(i = 1; i <= n; i++) {
      out << sol[i] << ' ';
   }

   return 0;
}