Cod sursa(job #2538051)

Utilizator radustn92Radu Stancu radustn92 Data 4 februarie 2020 12:36:01
Problema 2SAT Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <cstdio>
#include <vector>
using namespace std;

const int NMAX = 100505;
int N, M;
vector<int> G[NMAX], GT[NMAX];

inline int notNode(int node) {
	return node <= N ? node + N : node - N;
}

inline int nodeNotation(int node) {
	return node < 0 ? -node + N : node;
}

void addEdge(int x, int y) {
	G[x].push_back(y);
	GT[y].push_back(x);
}

void addOrEdge(int x, int y) {
	addEdge(notNode(x), y);
	addEdge(notNode(y), x);
}

void read() {
	scanf("%d%d", &N, &M);
	int x, y;
	for (int edgeIdx = 0; edgeIdx < M; edgeIdx++) {
		scanf("%d%d", &x, &y);
		x = nodeNotation(x); y = nodeNotation(y);
		addOrEdge(x, y);
	}
}

void dfsNormalGraph(int node, vector<bool>& visited, vector<int>& sortedByExitTime) {
	visited[node] = true;
	for (auto& neighbour : G[node]) {
		if (!visited[neighbour]) {
			dfsNormalGraph(neighbour, visited, sortedByExitTime);
		}
	}

	sortedByExitTime.push_back(node);
}

void dfsTransposeGraph(int node, vector<int>& component, int componentIdx) {
	component[node] = componentIdx;
	for (auto& neighbour : GT[node]) {
		if (component[neighbour] == -1) {
			dfsTransposeGraph(neighbour, component, componentIdx);
		}
	}
}

void solve() {
	vector<int> sortedByExitTime;
	vector<bool> visited(2 * N + 1, false);
	for (int node = 1; node <= 2 * N; node++) {
		if (!visited[node]) {
			dfsNormalGraph(node, visited, sortedByExitTime);
		}
	}

	reverse(sortedByExitTime.begin(), sortedByExitTime.end());
	vector<int> component(2 * N + 1, -1);
	int componentIdx = 0;
	for (auto& node : sortedByExitTime) {
		if (component[node] == -1) {
			dfsTransposeGraph(node, component, ++componentIdx);
		}
	}

	for (int node = 1; node <= N; node++) {
		if (component[node] == component[notNode(node)]) {
			printf("-1\n");
			return;
		}
	}

	for (int node = 1; node <= N; node++) {
		printf("%d ", component[node] > component[notNode(node)]);
	}
	printf("\n");
}

int main() {
	freopen("2sat.in", "r", stdin);
	freopen("2sat.out", "w", stdout);

	read();
	solve();
	return 0;
}