Cod sursa(job #2719706)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 10 martie 2021 10:27:14
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>

using namespace std;

const int N = 200000 + 7;
int n, m, top, o[N], tip[N], cur;
bool one[N], vis[N];
vector<int> g[N], ginv[N];

void dfs1(int a) {
  vis[a] = 1;
  for (auto &b : g[a]) {
    if (!vis[b]) {
      dfs1(b);
    }
  }
  o[++top] = a;
}

void dfs2(int a) {
  vis[a] = 1;
  tip[a] = cur;
  for (auto &b : ginv[a]) {
    if (!vis[b]) {
      dfs2(b);
    }
  }
}

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

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

signed main() {
  freopen ("2sat.in", "r", stdin);
  freopen ("2sat.out", "w", stdout);
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int x, y;
    scanf("%d %d", &x, &y);
    g[inv(code(x))].push_back(code(y));
    g[inv(code(y))].push_back(code(x));
  }
  for (int i = 1; i <= 2 * n; i++) {
    for (auto &j : g[i]) {
      ginv[j].push_back(i);
    }
  }
  for (int i = 1; i <= 2 * n; i++) {
    if (!vis[i]) {
      dfs1(i);
    }
  }
  for (int i = 1; i <= 2 * n; i++) {
    vis[i] = 0;
  }
  for (int i = 2 * n; i >= 1; i--) {
    int node = o[i];
    if (!vis[node]) {
      cur++;
      dfs2(node);
    }
  }
  for (int i = 1; i <= n; i++) {
    if (tip[i] == tip[inv(i)]) {
      printf("-1\n");
      return 0;
    }
  }
  for (int i = 1; i <= n; i++) {
    printf("%d ", tip[i] > tip[inv(i)]);
  }
  printf("\n");
}