Cod sursa(job #2674351)

Utilizator vladth11Vlad Haivas vladth11 Data 18 noiembrie 2020 22:37:30
Problema 2SAT Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define debug(x) cerr << #x << " " << x << "\n"
#define debug_with_space(x) cerr << #x << " " << x << " "

using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair <ll, ll> pii;
typedef pair <ll, pii> piii;
typedef tree <pii, null_type, less <pii>, rb_tree_tag, tree_order_statistics_node_update> OST;

const ll NMAX = 100001;
const ll INF = (1 << 16) - 1;
const ll MOD = 1000000007;
const ll BLOCK = 101;
const ll nr_of_bits = 20;

vector <int> v[NMAX], g[NMAX];
int inv[NMAX];
int viz[NMAX];
int stiva[NMAX];
int cnt = 0;
int comp[NMAX];

void DFS(int node){
    viz[node] = 1;
    for(auto x : v[node]){
        if(!viz[x])
            DFS(x);
    }
    stiva[++stiva[0]] = node;
}

void DFS2(int node){
    viz[node] = 2;
    comp[node] = cnt;
    for(auto x : g[node]){
        if(viz[x] == 1)
            DFS2(x);
    }
}

int main() {
    ifstream cin("2sat.in");
    ofstream cout("2sat.out");
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, i;
    int m;
    cin >> n >> m;
    for(i = 1; i <= 2 * n; i++){
        int x = i;
        if(x > n)
            x -= n;
        else
            x += n;
        inv[i] = x;
    }
    for(i = 1; i <= m; i++){
        int x, y;
        cin >> x >> y;
        if(x < 0)
            x = inv[-x];
        if(y < 0)
            y = inv[-y];
        v[inv[x]].push_back(y);
        v[inv[y]].push_back(x);

        g[y].push_back(inv[x]);
        g[x].push_back(inv[y]);
    }
    for(i = 1; i <= 2 * n; i++){
        if(!viz[i])
            DFS(i);
    }
    for(i = stiva[0]; i > 0; i--){
        if(viz[stiva[i]] == 1){
            cnt++;
            DFS2(stiva[i]);
        }
    }
    int ok = 1;
    for(int i = 1; i <= n; i++){
        if(comp[i] == comp[inv[i]])
            ok = 0;
    }
    if(!ok){
        cout << "-1\n";
        return 0;
    }
    for(i = 1; i <= n; i++){

        cout << (comp[i] > comp[inv[i]]) << " ";
    }
    return 0;
}