Pagini recente » Cod sursa (job #2717217) | Cod sursa (job #2758861) | Cod sursa (job #650693) | Cod sursa (job #1433341) | Cod sursa (job #2542476)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
const int NMAX = 2 * 1e5 + 5;
ifstream cin ("2sat.in");
ofstream cout ("2sat.out");
int n, m;
vector <int> g1[NMAX];
vector <int> g2[NMAX];
bool viz[NMAX];
vector <int> nodes;
vector <int> ctc[NMAX];
int comp[NMAX];
int val[NMAX];
int notn(int a)
{
if(a <= n)
return a + n;
else
return a - n;
}
void dfs1(int node)
{
viz[node] = 1;
for(auto x: g1[node]) {
if(viz[x] == 0) {
dfs1(x);
}
}
nodes.push_back(node);
}
vector <int> sortaret;
void dfs2(int node, int cnt)
{
viz[node] = 1;
ctc[cnt].push_back(node);
comp[node] = cnt;
for(auto x: g2[node]) {
if(viz[x] == 0) {
dfs2(x, cnt);
}
}
sortaret.push_back(node);
}
int main() {
cin >> n >> m;
vector < pair <int, int> > v;
for(int i = 1; i <= m; ++i) {
int x, y;
cin >> x >> y;
v.emplace_back(x, y);
if (x < 0) x = abs(x);
else x += n;
if (y < 0) y = abs(y);
else y += n;
g1[notn(x)].push_back(y);
g1[notn(y)].push_back(x);
// cout << notn(x) << ' ' << y << endl;
// cout << notn(y) << ' ' << x << endl;
g2[y].push_back(notn(x));
g2[x].push_back(notn(y));
}
for(int i = 1; i <= 2 * n; ++i) {
if(viz[i] == 0) {
dfs1(i);
}
}
reverse(nodes.begin(), nodes.end());
for(int i = 0; i <= 2 * n; ++i)
viz[i] = 0;
int cnt = 0;
for(auto x: nodes) {
if(viz[x] == 0) {
++cnt;
dfs2(x, cnt);
}
}
for(int i = 1; i <= 2 * n; ++i)
val[i] = -1;
reverse(sortaret.begin(), sortaret.end());
for(auto x: sortaret) {
// cout << x << " ";
if(val[notn(x)] != -1) {
val[x] = 1 - val[notn(x)];
} else {
val[x] = 0;
}
}
// cout << "\n";
bool sol = 1;
for(auto x: sortaret) {
for(auto y: g2[x]) {
if(val[x] == 1 && val[y] == 0) {
sol = 0;
break;
}
}
}
if(sol == 0) {
cout << "-1\n";
return 0;
}
for(int i = 1; i <= n; ++i) {
cout << val[i] << " ";
}
cout << "\n";
return 0;
}