Cod sursa(job #3292499)

Utilizator TeodorLuchianovTeo Luchianov TeodorLuchianov Data 8 aprilie 2025 13:33:26
Problema 2SAT Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

int const NMAX = 2e5;
vector <int> g[1 + NMAX];
int ind = 0;
int visit[1 + NMAX];
int minReach[1 + NMAX];
bool onStack[1 + NMAX];

stack <int> st;

int comp[1 + NMAX];

int strongInd = 0;
vector <int> strong[1 + NMAX];

void computeTarjan(int node) {

  ind++;
  visit[node] = ind;
  minReach[node] = visit[node];
  st.push(node);
  onStack[node] = true;
  for(int i = 0;i < g[node].size();i++) {
    int to = g[node][i];
    if(visit[to] == 0) {
      computeTarjan(to);
      minReach[node] = min(minReach[node], minReach[to]);
    } else if(onStack[to]) {
      minReach[node] = min(minReach[node], visit[to]);
    }
  }
  if(minReach[node] == visit[node]) {
    strongInd++;
    while(st.top() != node) {
      int temp = st.top();
      st.pop();
      comp[temp] = strongInd;
      strong[strongInd].push_back(temp); 
    } 
    st.pop();
    comp[node] = strongInd;
    strong[strongInd].push_back(node);
  }
}

int ans[1 + NMAX];

int getNode(int val, int n) {
  if(val < 0) {
    val = -val;
    val += n;
  }
  return val;
}
int main() {
  
  int n, m;
  in >> n >> m;
  for(int i = 1;i <= m;i++) {
    int a, b, notA, notB;
    in >> a >> b; 
    notA = -a;
    notB = -b;
    g[getNode(notA, n)].push_back(getNode(b, n));
    g[getNode(notB, n)].push_back(getNode(a, n));
  }
  for(int i = 1;i <= n+n;i++) {
    if(visit[i] == 0) {
      computeTarjan(i);
    }
  }
  bool isSol = true;
  for(int i = 1;i <= n;i++) {
    ans[i] = -1;
    if(comp[i] == comp[i+n]) {
      isSol = false;
    }
  }
  if(!isSol) {
    out << "-1\n"; 
    return 0;
  }
  for(int i = 1;i <= strongInd;i++) {
    for(int j = 0;j < strong[i].size();j++) {
      int temp = strong[i][j];
      int val = 1;
      if(temp >= n) {
	temp -= n;
	val = 0;
      }
      if(ans[temp] == -1) {
	ans[temp] = val; 
      }
    }
  }
  for(int i = 1;i <= n;i++) {
    out << ans[i] << ' ';
  }
  return 0;
}