Cod sursa(job #2233648)

Utilizator Cristian1997Vintur Cristian Cristian1997 Data 23 august 2018 19:46:09
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using ll = long long;
using pii = pair<int, int>;
#define dbg(x) cerr<<#x": "<<(x)<<'\n'
#define dbg_p(x) cerr<<#x": "<<(x).first<<' '<<(x).second<<'\n'
#define dbg_v(x, n) {cerr<<#x"[]: ";for(long long _=0;_<n;++_)cerr<<(x)[_]<<' ';cerr<<'\n';}
#define all(v) v.begin(), v.end()
#define fi first
#define se second
#define INF 2000000010
#define MOD 1000000007
#define ST_SIZE 1048600
#define QMAX 
#define NMAX 200010

int n, nr;
vector<int> adj[NMAX], adjt[NMAX], ord, nodes[NMAX];
bool vis[NMAX];
int val[NMAX], comp[NMAX], in[NMAX];

void addEdge(int x, int y) {
	x = (x > 0 ? 2 * x - 1 : -2 * x - 2);
	y = (y > 0 ? 2 * y - 1 : -2 * y - 2);
	
	adj[x].push_back(y);
	adjt[y].push_back(x);
}

void dfs(int v) {
	vis[v] = true;
	for(auto u : adj[v]) if(!vis[u]) dfs(u);
	
	ord.push_back(v);
}

void dfst(int v) {
	vis[v] = true;
	comp[v] = nr;
	nodes[nr].push_back(v);
	for(auto u : adjt[v]) if(!vis[u]) dfst(u);
}

int main()
{
	ios_base::sync_with_stdio(false);
	freopen("2sat.in", "r", stdin);
	freopen("2sat.out", "w", stdout);
	
	int i, m, x, y;
	
	cin >> n >> m;
	for(i = 1; i <= m; ++i) {
		cin >> x >> y;
		addEdge(-x, y);
		addEdge(-y, x);
	}
	
	for(i = 0; i < 2 * n; ++i) if(!vis[i]) dfs(i);
	
	memset(vis, 0, sizeof vis);
	for(i = 2 * n - 1; i >= 0; --i) if(!vis[ord[i]]) dfst(ord[i]), ++nr;
	
	for(i = 0; i < 2 * n; ++i) if(comp[i] == comp[i ^ 1]) return cout << -1 << '\n', 0;
	
	for(i = 0; i < 2 * n; ++i) for(auto u : adj[i]) if(comp[i] != comp[u]) ++in[comp[u]];
	
	memset(val, -1, sizeof val);
	
	// for(i = 0; i < nr; ++i) dbg_v(nodes[i], nodes[i].size());
	
	queue<int> q;
	for(i = 0; i < nr; ++i) if(!in[i]) q.push(i);
	while(!q.empty()) {
		for(auto v : nodes[q.front()]) {
			if(val[v] == -1) val[v] = 0, val[v ^ 1] = 1;
			
			for(auto u : adj[v]) if(comp[v] != comp[u] && (--in[comp[u]]) == 0) q.push(comp[u]);
		}
		
		q.pop();
	}
	
	for(i = 1; i < 2 * n; i += 2) cout << (val[i] == -1 ? 1 : val[i]) << ' ';
	cout << '\n';
	
	return 0;
}