Pagini recente » Cod sursa (job #2735083) | Cod sursa (job #2274025) | Monitorul de evaluare | Cod sursa (job #2735105) | Cod sursa (job #3329498)
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector <int> v[200005][2], muchii[200005], stiva, componenta;
int f[200005], comp[200005], grad_in[200005], ras[200005];
vector <vector <int>> componente;
queue <int> q;
void dfs( int x, int tip ){
int i, y;
if( tip == 1 ){
componenta.push_back( x );
comp[x] = componente.size();
//cout << x << ' ';
}
for( i = 0; i < v[x][tip].size(); i++ ){
y = v[x][tip][i];
if( f[y] == tip ){
f[y] = tip + 1;
dfs( y, tip );
}
}
if( tip == 0 ){
stiva.push_back( x );
}
}
int main(){
int n, m, i, j, x, y, ok;
ifstream fin( "2sat.in" );
ofstream fout( "2sat.out" );
fin >> n >> m;
for( i = 0; i < m; i++ ){
fin >> x >> y;
if( x < 0 ){
x = -x + n;
}
if( y < 0 ){
y = -y + n;
}
x--;
y--;
v[( x + n ) % ( 2 * n )][0].push_back( y );
v[( y + n ) % ( 2 * n )][0].push_back( x );
v[y][1].push_back( ( x + n ) % ( 2 * n ) );
v[x][1].push_back( ( y + n ) % ( 2 * n ) );
}
for( i = 0; i < 2 * n; i++ ){
if( f[i] == 0 ){
f[i] = 1;
dfs( i, 0 );
}
}
for( i = stiva.size() - 1; i >= 0; i-- ){
if( f[stiva[i]] == 1 ){
f[stiva[i]] = 2;
dfs( stiva[i], 1 );
componente.push_back( componenta );
componenta.clear();
//cout << '\n';
}
}
for( i = 0; i < 2 * n; i++ ){
for( j = 0; j < v[i][0].size(); j++ ){
x = comp[i];
y = comp[v[i][0][j]];
if( x != y ){
muchii[x].push_back( y );
grad_in[y]++;
//cout << x << ' ' << y << '\n';
}
}
}
for( i = 0; i < componente.size(); i++ ){
if( grad_in[i] == 0 ){
q.push( i );
//cout << i << '\n';
}
}
ok = 1;
while( q.empty() == false && ok == 1 ){
x = q.front();
q.pop();
if( f[x] != 3 ){
y = comp[( componente[x][0] + n ) % ( 2 * n )];
if( x == y ){
ok = 0;
continue;
}
//cout << x << ' ' << y << '\n';
for( i = 0; i < componente[y].size(); i++ ){
ras[componente[y][i]] = 1;
}
f[y] = 3;
for( i = 0; i < muchii[x].size(); i++ ){
y = muchii[x][i];
grad_in[y]--;
if( grad_in[y] == 0 ){
q.push( y );
}
}
}
}
if( ok == 0 ){
fout << -1;
}
else{
for( i = 0; i < n; i++ ){
fout << ras[i] << ' ';
}
}
return 0;
}