Pagini recente » Rating Covaciu Andrei (piticutzu15) | Cod sursa (job #3201659) | Rating Bilescu Adrian (diti) | Cod sursa (job #3291919) | Cod sursa (job #3292499)
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream in("2sat.in");
ofstream out("2sat.out");
int const NMAX = 2e5;
vector <int> g[1 + NMAX];
int ind = 0;
int visit[1 + NMAX];
int minReach[1 + NMAX];
bool onStack[1 + NMAX];
stack <int> st;
int comp[1 + NMAX];
int strongInd = 0;
vector <int> strong[1 + NMAX];
void computeTarjan(int node) {
ind++;
visit[node] = ind;
minReach[node] = visit[node];
st.push(node);
onStack[node] = true;
for(int i = 0;i < g[node].size();i++) {
int to = g[node][i];
if(visit[to] == 0) {
computeTarjan(to);
minReach[node] = min(minReach[node], minReach[to]);
} else if(onStack[to]) {
minReach[node] = min(minReach[node], visit[to]);
}
}
if(minReach[node] == visit[node]) {
strongInd++;
while(st.top() != node) {
int temp = st.top();
st.pop();
comp[temp] = strongInd;
strong[strongInd].push_back(temp);
}
st.pop();
comp[node] = strongInd;
strong[strongInd].push_back(node);
}
}
int ans[1 + NMAX];
int getNode(int val, int n) {
if(val < 0) {
val = -val;
val += n;
}
return val;
}
int main() {
int n, m;
in >> n >> m;
for(int i = 1;i <= m;i++) {
int a, b, notA, notB;
in >> a >> b;
notA = -a;
notB = -b;
g[getNode(notA, n)].push_back(getNode(b, n));
g[getNode(notB, n)].push_back(getNode(a, n));
}
for(int i = 1;i <= n+n;i++) {
if(visit[i] == 0) {
computeTarjan(i);
}
}
bool isSol = true;
for(int i = 1;i <= n;i++) {
ans[i] = -1;
if(comp[i] == comp[i+n]) {
isSol = false;
}
}
if(!isSol) {
out << "-1\n";
return 0;
}
for(int i = 1;i <= strongInd;i++) {
for(int j = 0;j < strong[i].size();j++) {
int temp = strong[i][j];
int val = 1;
if(temp >= n) {
temp -= n;
val = 0;
}
if(ans[temp] == -1) {
ans[temp] = val;
}
}
}
for(int i = 1;i <= n;i++) {
out << ans[i] << ' ';
}
return 0;
}