Cod sursa(job #3156252)

Utilizator PetyAlexandru Peticaru Pety Data 10 octombrie 2023 23:39:01
Problema 2SAT Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
#define sz(x) x.size()
#define all(x) x.begin(), x.end()

using namespace std;

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

using ll = long long;
using ld = long double;
const int N = 200002;

stack<int>st;
vector<int>G[N];
vector<int>G2[N];
int n, m, comp[N], viz[N], C;
int neg (int x) {
  return (x > n ? x - n : x + n);
}
int val (int x) {
  return (x > 0 ? x : -x + n);
}

void dfs1 (int nod) {
  viz[nod] = 1;
  for (int it : G[nod]) 
    if (!viz[it])
      dfs1(it);
  st.push(nod);
}

void dfs2 (int nod) {
  comp[nod] = C;
  viz[nod] = 1;
  for (int it : G2[nod])
    if (!viz[it])
      dfs2(it);
}

int main () 
{
  ios_base::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);
  fin >> n >> m;
  for (int i = 1; i <= m; i++) {
    int x, y;
    fin >> x >> y;
    x = val(x);
    y = val(y);
    G[neg(x)].push_back(y);
    G[neg(y)].push_back(x);
    G2[x].push_back(neg(y));
    G2[y].push_back(neg(x));
  }
  for (int i = 1; i <= n; i++)
    if (!viz[i])
      dfs1(i);
  memset(viz, 0, sizeof(viz));
  while (st.size()) {
    if (!viz[st.top()]) {
      C++;
      dfs2(st.top());
    }
    st.pop();
  }
  bool ok = 1;
  for (int i = 1; i <= n; i++)
    if (comp[i] == comp[i + n])
      ok = 0;
  if (!ok) {
    fout << -1;
    return 0;
  }
  for (int i = 1; i <= n; i++)
    fout << (comp[i] > comp[i + n]) << " ";
  return 0;
}