Pagini recente » Cod sursa (job #141032) | Cod sursa (job #810927) | Cod sursa (job #1915846) | Cod sursa (job #1141698) | Cod sursa (job #2730140)
#include <iostream>
#include <cstdio>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("2sat.in");
ofstream fout("2sat.out");
const int N = 100000;
const int M = 200000;
vector <int> graph[2*N + 1];
vector <int> graph_inv[2*N + 1];
vector <int> top;
int sol[2*N + 1];
bool completed[2*N + 1];
bool visited[2*N + 1];
bool visited_inv[2*N + 1];
bool impossible;
int get_node(int nodeValue, int n){
return nodeValue + n;
}
int inv(int nodeValue, int n){
return get_node(-nodeValue, n);
}
void add_edge(int x, int y, int n){
graph[inv(x, n)].push_back(get_node(y, n));
graph[inv(y, n)].push_back(get_node(x, n));
graph_inv[get_node(y, n)].push_back(inv(x, n));
graph_inv[get_node(x, n)].push_back(inv(y, n));
}
void dfs(int node, int n){
int nodeValue = get_node(node, n);
visited[nodeValue] = true;
for(int p = 0; p < (int)graph[nodeValue].size(); p++){
int nextValue = graph[nodeValue][p];
if(!visited[nextValue])
dfs(nextValue - n, n);
}
top.push_back(node);
}
void dfs_inv(int node, int n){
int nodeValue = get_node(node, n);
int invValue = inv(node, n);
if(!completed[nodeValue]){
completed[nodeValue] = completed[invValue] = true;
sol[nodeValue] = 0, sol[invValue] = 1;
}
else
impossible = true;
visited_inv[nodeValue] = true;
for(int p = 0; p < (int)graph_inv[nodeValue].size(); p++){
int nextValue = graph_inv[nodeValue][p];
if(!visited_inv[nextValue])
dfs_inv(nextValue - n, n);
}
}
int main()
{
int n, m, i, j, x, y;
fin >> n >> m;
for(i = 0; i < m; i++){
fin >> x >> y;
add_edge(x, y, n);
}
for(i = -n; i <= n; i++)
if(!visited[get_node(i, n)] && i)
dfs(i, n);
for(i = -n; i <= n; i++)
sol[get_node(i, n)] = -1;
for(i = (int)top.size() - 1; i >= 0; i--)
if(!visited_inv[get_node(top[i], n)] && !completed[get_node(top[i], n)])
dfs_inv(top[i], n);
if(impossible)
fout << "-1\n";
else
for(i = 1; i <= n; i++)
fout << sol[get_node(i, n)] << ' ';
return 0;
}