Cod sursa(job #1414370)

Utilizator darrenRares Buhai darren Data 2 aprilie 2015 16:01:35
Problema 2SAT Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <cstring>
#include <fstream>
#include <algorithm>
#include <vector>

using namespace std;

int N, M;
vector<int> V[200002];
int E1[200002], E2[200002];
int ST[200002];
bool S[200002], val[200002];
bool done[200002];

inline int op(int x)
{
	return (x <= N ? x + N : x - N);
}

void Dfs(int x)
{
	S[x] = true;
	for (auto nod : V[x])
		if (!S[nod])
			Dfs(nod);
	ST[++ST[0]] = x;
}

int main()
{
	ifstream fin("2sat.in");
	ofstream fout("2sat.out");
	
	fin >> N >> M;
	for (int i = 1, nod1, nod2; i <= M; ++i)
	{
		fin >> nod1 >> nod2;
		if (nod1 < 0) nod1 = N - nod1;
		if (nod2 < 0) nod2 = N - nod2;
		
		E1[i] = nod1;
		E2[i] = nod2;
		
		V[op(nod1)].push_back(nod2);
		V[op(nod2)].push_back(nod1);
	}
	
	for (int i = 1; i <= 2 * N; ++i)
		if (!S[i])
			Dfs(i);
	
	for (int i = ST[0]; i >= 1; --i)
		if (!done[op(ST[i])])
			done[ST[i]] = true;
		else
			val[ST[i]] = !val[op(ST[i])];
	
	bool ok = true;
	for (int i = 1; i <= M; ++i)
		if (!val[E1[i]] && !val[E2[i]])
			ok = false;
	
	if (!ok)
		fout << -1 << '\n';
	else
	{
		for (int i = 1; i <= N; ++i)
			fout << val[i] << ' ';
		fout << '\n';
	}
	
	fin.close();
	fout.close();
}