Cod sursa(job #2978187)

Utilizator DKMKDMatei Filibiu DKMKD Data 13 februarie 2023 12:34:45
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX=2e5;
vector<int>g[NMAX+5],rg[NMAX+5],topsort;
int comp[NMAX+5],n,ctc,m;
bitset<NMAX+5>viz;
int val_asoc(int x){
  if(x<0)
    return -x+n;
  return x;
}
int neg(int x){
  if(x<=n)
    return x+n;
  return x-n;
}
void dfs(int x){
  viz[x]=1;
  for(auto &y:g[x])
    if(!viz[y])
     dfs(y);
  topsort.push_back(x);
}
void dfs2(int x){
  comp[x]=ctc;
  for(auto &y:rg[x])
    if(!comp[y])
      dfs2(y);
}
void read(){
  fin>>n>>m;
  for(int i=0;i<m;++i){
    int x,y;
    fin>>x>>y;
    x=val_asoc(x);
    y=val_asoc(y);
  g[neg(x)].push_back(y);
  g[neg(y)].push_back(x);
  rg[y].push_back(neg(x));
  rg[x].push_back(neg(y));
  }
}
void solve(){
  for(int i=1;i<=2*n;++i)
    if(!viz[i])
      dfs(i);
  reverse(topsort.begin(),topsort.end());
  for(auto &y:topsort){
    if(comp[y])
      continue;
    ctc++;
    dfs2(y);
  }
  bool _2sat=1;
  for(int i=1;i<=n;++i)
    if(comp[i]==comp[i+n])
      _2sat=0;
  if(_2sat==0){
    fout<<"-1";
    return;
  }
  for(int i=1;i<=n;++i)
    if(comp[i]>comp[i+n])
      fout<<1<<" ";
    else
      fout<<0<<" ";
}
int main(){
 read();
 solve();
 return 0;
}