Cod sursa(job #1486008)

Utilizator vladrochianVlad Rochian vladrochian Data 13 septembrie 2015 16:14:06
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
#include <stack>
#include <cstring>
using namespace std;

const int kMaxNodes = 200005;

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

int N;
vector<int> g[kMaxNodes];
vector<int> gt[kMaxNodes];

bool use[kMaxNodes];
stack<int> st;

bool val[kMaxNodes], no_sol;

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

void AddEdge(int x, int y) {
  g[x].push_back(y);
  gt[y].push_back(x);
}

void Init() {
  int M;
  fin >> N >> M;
  while (M--) {
    int x, y;
    fin >> x >> y;
    if (x < 0) x = -x + N;
    if (y < 0) y = -y + N;
    AddEdge(Not(x), y);
    AddEdge(Not(y), x);
  }
}

void SortDfs(int node) {
  use[node] = true;
  for (int i : g[node])
    if (!use[i])
      SortDfs(i);
  st.push(node);
}

void SolveDfs(int node) {
  if (val[node])
    no_sol = true;
  use[node] = true;
  val[Not(node)] = true;
  for (int i : gt[node])
    if (!use[i])
      SolveDfs(i);
}

void Solve() {
  for (int i = 1; i <= 2 * N; ++i)
    if (!use[i])
      SortDfs(i);
  memset(use, 0, sizeof use);
  while (!st.empty()) {
    int node = st.top();
    st.pop();
    if (!use[node] && !use[Not(node)])
      SolveDfs(node);
  }
}

void Print() {
  if (no_sol) {
    fout << "-1\n";
  } else {
    for (int i = 1; i <= N; ++i)
      fout << int(val[i]) << " ";
    fout << "\n";
  }
}

int main() {
  Init();
  Solve();
  Print();
  return 0;
}