Cod sursa(job #945062)

Utilizator AnonymouslegionAnonymous Anonymouslegion Data 30 aprilie 2013 12:45:49
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include<fstream>
#include<vector>

using namespace std;

int n;

vector<int> graph[200005], gt[200005];

inline int no(int x){
  if(x > n)
    return x - n;
  return x + n;
}

void implying(int x, int y){
  if(x < 0)
    x = -x + n;
  if(y < 0)
    y = -y + n;
  graph[no(x)].push_back(y);
  graph[no(y)].push_back(x);
  gt[x].push_back(no(y));
  gt[y].push_back(no(x));
}

vector<int> st;
int impossible, vis[200005], vis2[200005], val[200005];

void dfs1(int x){
  vis[x] = 1;
  for(int i = 0; i < graph[x].size(); ++i)
    if(!vis[graph[x][i]])
      dfs1(graph[x][i]);
  st.push_back(x);
}

void dfs2(int x){
  if(val[x] == 1)
    impossible = 1;
  val[no(x)] = 1;
  vis2[x] = 1;
  for(int i = 0; i < gt[x].size(); ++i)
    if(!vis2[gt[x][i]])
      dfs2(gt[x][i]);
}

int main(){
  ifstream in("2sat.in");
  ofstream out("2sat.out");

  int m;
  in >> n >> m;

  for(int i = 1; i <= m; ++i){
    int x, y;
    in >> x >> y;
    implying(x, y);
  }

  for(int i = 1; i <= 2 * n; ++i)
    if(!vis[i])
      dfs1(i);

  for(int i = 2 * n - 1; i >= 0; --i)
    if(!vis2[st[i]] && !vis2[no(st[i])])
      dfs2(st[i]);

  if(impossible)
    out << "-1";
  else
    for(int i = 1; i <= n; ++i)
      out << val[i] << " ";

  return 0;
}