Cod sursa(job #2797763)

Utilizator iancupoppPopp Iancu Alexandru iancupopp Data 10 noiembrie 2021 16:07:39
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <vector>

using namespace std;

const int N = 2e5 + 5;

vector<int> nxt[N], prv[N], top;
bool viz1[N], viz2[N];
int con[N], nr_con;

void dfs1(int nod) {
  viz1[nod] = true;
  for (auto vec : nxt[nod])
    if (!viz1[vec])
      dfs1(vec);
  top.push_back(nod);
}

void dfs2(int nod) {
  viz2[nod] = true;
  con[nod] = nr_con;
  for (auto vec : prv[nod])
    if (!viz2[vec])
      dfs2(vec);
}

int main() {
  ifstream cin("2sat.in");
  ofstream cout("2sat.out");
  int n, m;
  cin >> n >> m;
  while (m--) {
    int x, y;
    cin >> x >> y;
    int a, b, not_a, not_b;
    if (x > 0)
      a = 2 * x, not_a = 2 * x + 1;
    else
      a = -2 * x + 1, not_a = -2 * x;
    if (y > 0)
      b = 2 * y, not_b = 2 * y + 1;
    else
      b = -2 * y + 1, not_b = -2 * y;
    nxt[not_a].push_back(b);
    prv[b].push_back(not_a);
    nxt[not_b].push_back(a);
    prv[a].push_back(not_b);
  }
  cin.close();
  for (int i = 2; i <= 2 * n + 1; ++i)
    if (!viz1[i])
      dfs1(i);
  for (auto i = top.rbegin(); i != top.rend(); ++i)
    if (!viz2[*i]) {
      dfs2(*i);
      ++nr_con;
    }
  vector<bool> ans;
  for (int i = 2; i <= 2 * n; i += 2) {
    if (con[i] == con[i + 1]) {
      cout << "-1\n";
      cout.close();
      return 0;
    }
    ans.push_back(con[i] > con[i + 1]);
  }
  for (auto i : ans)
    cout << i << " ";
  cout.close();
  return 0;
}