Cod sursa(job #2236063)

Utilizator pas.andreiPopovici Andrei-Sorin pas.andrei Data 28 august 2018 00:47:42
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define NMAX 200005
#define INF 0x3f3f3f3f
#define MOD 1000003
#define pb push_back
#define x first
#define y second

using namespace std;

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

vector<int> G[NMAX], GT[NMAX];
stack<int> st;
bool val[NMAX],viz[NMAX],ok=1;
int n,m,i,x,y;

inline int positivizare(int x) {
	if(x>0) return x;
	return n-x;
}

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

void DFSp(int x) {
	viz[x] = 1;

	for(auto it:G[x])
		if(!viz[it]) DFSp(it);

	st.push(x);
}

void DFSm(int x) {
	viz[x] = 0;

	if(val[x]) ok=0;
	val[negat(x)] = 1;

	for(auto it:GT[x])
		if(viz[it]) DFSm(it);
}

int main() {
	fin >> n>> m;

	for(i=1;i<=m;++i) {
		fin >>x>>y;

		x = positivizare(x);
		y = positivizare(y);

		G[negat(x)].pb(y);
		G[negat(y)].pb(x);

		GT[y].pb(negat(x));
		GT[x].pb(negat(y));
	}

	for(i=1;i<=2*n;++i)
		if(!viz[i]) DFSp(i);

	while(!st.empty()) {
		if(viz[st.top()] && viz[negat(st.top())])
			DFSm(st.top());
		st.pop();
	}

	if(!ok) fout << -1;
	else {
		for(i=1;i<=n;++i)
			fout << val[i] << ' ';
	}

	return 0;
}