Pagini recente » Cod sursa (job #3191913) | Cod sursa (job #2356364) | Cod sursa (job #238457) | Cod sursa (job #1166510) | Cod sursa (job #2975583)
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>
using namespace std;
ifstream cin("2sat.in");
ofstream cout("2sat.out");
const int NMAX = 2e5;
vector <int> g[NMAX + 1], rg[NMAX + 1], topsort;
int comp[NMAX + 1], n, ctc;
bitset <NMAX + 1> viz;
int val_asoc(int x){
// deoarece -x corespunde lui !x, iar noi negăm un x (<= n) cu x + n, x (< 0) devine echivalent cu -x + n
if(x < 0)
return -x + n;
return x;
}
int neg(int x){
// negăm x in funcție de valorea sa față de n
if(x <= n)
return x + n;
// ex: dacă x = -5 înseamnă ~5. El se va transforma din cauza negației în -(-5) + n = 5 + n, iar ~(~5) = 5, deci
// vom scădea n pentru a obține rezultatul 5
return x - n;
}
void dfs(int x){
viz[x] = 1;
for(auto &y : g[x])
if(!viz[y])
dfs(y);
topsort.push_back(x);
}
void dfs2(int x){
comp[x] = ctc;
for(auto &y : rg[x])
if(!comp[y])
dfs2(y);
}
int main(){
int m = 0;
cin >> n >> m;
for(int i = 0; i < m; i++){
int x = 0, y = 0;
cin >> x >> y;
x = val_asoc(x);
y = val_asoc(y);
g[neg(x)].push_back(y);
g[neg(y)].push_back(x);
rg[y].push_back(neg(x));
rg[x].push_back(neg(y));
}
for(int i = 1; i <= 2 * n; i++)
if(!viz[i])
dfs(i);
reverse(topsort.begin(), topsort.end());
for(auto &y : topsort){
if(comp[y])
continue;
ctc++;
dfs2(y);
}
bool _2sat = 1;
for(int i = 1; i <= n; i++)
if(comp[i] == comp[i + n])
_2sat = 0;
if(_2sat == 0){
cout << "-1";
return 0;
}
for(int i = 1; i <= n; i++)
if(comp[i] < comp[i + n])
cout << 0 << " ";
else
cout << 1 << " ";
}