Pagini recente » Borderou de evaluare (job #966730) | Cod sursa (job #353811) | Cod sursa (job #3256059) | Cod sursa (job #2381223) | Cod sursa (job #2623496)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("2sat.in");
ofstream fout ("2sat.out");
const int N = 2e5 + 2;
int n, m;
vector<int>G[N], Gr[N];
vector<vector<int> > ctc;
bool viz[N];
int comp[N], val[N];
int valNod (int x) {
if (x < 0)
return -x + n;
return x;
}
int neg (int x){
if (x > n)
return x - n;
return x + n;
}
stack<int>st;
void dfs1 (int x) {
viz[x] = 1;
for (auto it : G[x]) {
if (!viz[it])
dfs1(it);
}
st.push(x);
}
vector<int>c;
int cnt;
void dfs2 (int x) {
viz[x] = 1;
for (auto it : Gr[x]) {
if (!viz[it])
dfs2(it);
}
c.push_back(x);
comp[x] = cnt;
}
int main()
{
fin >> n >> m;
for (int i = 1; i <= m;i++) {
int x, y;
fin >> x >> y;
x = valNod(x);
y = valNod(y);
G[neg(x)].push_back(y);
G[neg(y)].push_back(x);
Gr[y].push_back(neg(x));
Gr[x].push_back(neg(y));
}
for (int i = 1; i <= 2 * n; i++)
if (!viz[i])
dfs1(i);
memset(val, -1, sizeof(val));
memset(viz, 0, sizeof(viz));
while (!st.empty()) {
int nod = st.top();
st.pop();
if (!viz[nod]) {
c.clear();
cnt++;
dfs2(nod);
ctc.push_back(c);
}
}
for (auto c : ctc) {
bool ok = 1;
for (auto it : c) {
if (comp[it] == comp[neg(it)])
ok = 0;
}
if (!ok) {
fout << -1;
return 0;
}
int a = -1;
for (auto it : c) {
if (val[it] != -1)
a = val[it];
if (a != -1 && val[it] != -1 && val[it] != a)
ok = 0;
}
if (!ok) {
fout << -1;
return 0;
}
if (a == -1)
a = 0;
for (auto it : c) {
val[it] = a;
if (val[neg(it)] != -1 && val[neg(it)] != 1 - a)
ok = 0;
val[neg(it)] = 1 - a;
}
if (!ok) {
fout << -1;
return 0;
}
}
for (int i = 1; i <= n; i++)
fout << val[i] << " ";
return 0;
}