Cod sursa(job #2665017)

Utilizator gavra_bogdanBogdan Gavra gavra_bogdan Data 29 octombrie 2020 21:41:56
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <vector>

const int nmax = 2e5 + 5;

std::vector<int>in[nmax], out[nmax], st;
int k, viz[nmax], ctc[nmax], ans[nmax], n;

void dfs(int node, int type) {
	viz[node] = type;
	if (type == 1) {
		for (int x : in[node]) if (!viz[x]) dfs(x, type);
		st.push_back(node);
	}
	else {
		ctc[node]=k;
		for (int x : out[node]) if (viz[x] == 1) dfs(x, type);
	}
}

int tr(int x, bool op) {
	if (op == 0 and x < 0) return -x;
	if (op == 0) return n + x;
	if (op == 1 and x < 0) return n-x;
	return x;
}

int main() {
	std::ifstream fin("2sat.in");
	std::ofstream fout("2sat.out");
	int m, u, v;
	fin >> n >> m;
	for (int i = 0; i < m; i++) {
		fin >> u >> v;
		in[tr(u, 0)].push_back(tr(v, 1));
		in[tr(v, 0)].push_back(tr(u, 1));
		out[tr(u, 1)].push_back(tr(v, 0));
		out[tr(v, 1)].push_back(tr(u, 0));
	}
	for (int i = 1; i <= 2 * n; i++)
		if (!viz[i]) dfs(i, 1);
	while (st.size()) {
		int x = st.back();
		st.pop_back();
		if (!(viz[x] - 1)) k++, dfs(x, 2);
	}
	for (int i = 1; i <= n; i++)
		if (ctc[i] == ctc[n + i]) {
			fout << "-1";
			return 0;
		}
		else ans[i] = (ctc[i] > ctc[n + i]);
	for (int i = 1; i <= n; i++) fout << ans[i] << " ";
}