Cod sursa(job #2572645)

Utilizator PopoviciRobertPopovici Robert PopoviciRobert Data 5 martie 2020 13:40:59
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.55 kb
#include <bits/stdc++.h>
#define lsb(x) (x & (-x))
#define ll long long
#define ull unsigned long long
#define uint unsigned int


using namespace std;

vector <vector <int>> g, gr;
vector <int> top, comp_id;
vector <bool> vis;

void dfs(int nod) {
    vis[nod] = 1;
    for(auto it : g[nod]) {
        if(vis[it] == 0) {
            dfs(it);
        }
    }
    top.push_back(nod);
}

void dfs_ctc(int nod, int id) {
    vis[nod] = 1;
    comp_id[nod] = id;
    for(auto it : gr[nod]) {
        if(vis[it] == 0) {
            dfs_ctc(it, id);
        }
    }
}

namespace Brut {
    vector <int> x, y;
    static int n, m;
    inline void Gen() {
        ofstream fout("A.in");
        n = rand() % 10 + 1, m = rand() % 5;
        int sz = 2 * n;
        fout << n << " " << m << "\n";
        x.resize(m), y.resize(m);
        for(int i = 0; i < m; i++) {
            x[i] = rand() % sz, y[i] = rand() % sz;
            x[i] = x[i] - n + (x[i] >= n);
            y[i] = y[i] - n + (y[i] >= n);
            fout << x[i] << " " << y[i] << "\n";
        }
        fout.close();
    }
};

int main() {
#ifdef HOME
    ifstream cin("A.in");
    ofstream cout("A.out");
#endif
    ifstream cin("2sat.in");
    ofstream cout("2sat.out");
    int i, n, m;
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n >> m;
    auto get = [&](int x) {
        return (x < 0 ? n - x : x);
    };
    auto Not = [&](int x) {
        return (x <= n ? x + n : x - n);
    };
    auto addEdge = [&](int x, int y) {
        g[x].push_back(y);
        gr[y].push_back(x);
    };

    g.resize(2 * n + 1), gr.resize(2 * n + 1);
    vector <int> x(m), y(m);
    for(i = 0; i < m; i++) {
        cin >> x[i] >> y[i];
        x[i] = get(x[i]), y[i] = get(y[i]);
        addEdge(Not(x[i]), y[i]);
        addEdge(Not(y[i]), x[i]);
    }

    vis.resize(2 * n + 1), comp_id.resize(2 * n + 1);
    for(i = 1; i <= 2 * n; i++) {
        if(vis[i] == 0) {
            dfs(i);
        }
    }
    fill(vis.begin(), vis.end(), 0);
    int id = 0;
    for(i = 2 * n - 1; i >= 0; i--) {
        if(vis[top[i]] == 0) {
            dfs_ctc(top[i], ++id);
        }
    }
    for(i = 1; i <= n; i++) {
        if(comp_id[i] == comp_id[Not(i)]) {
            cout << -1;
            return 0;
        }
    }
    vector <int> sol(2 * n + 1);
    for(i = 1; i <= 2 * n; i++) {
        sol[i] = (comp_id[i] > comp_id[Not(i)]);
    }
    for(i = 1; i <= n; i++) {
        cout << sol[i] << " ";
    }

    return 0;
}