Cod sursa(job #2514081)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 24 decembrie 2019 14:51:04
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;

constexpr int maxn = 1e5 + 10;

int n, m, val_buf[2 * maxn] = {}, *val = val_buf + maxn, viz_buf[2 * maxn], *viz = viz_buf + maxn;
vector<int> vec_buf[2 * maxn], *vec = vec_buf + maxn, inv_vec_buf[2 * maxn], *inv_vec = inv_vec_buf + maxn;

void dfs(int curr, vector<int>& st, const vector<int> * const vec, const int viz_target){
    if(viz[curr] != viz_target){
        viz[curr] = viz_target;
        for(auto next : vec[curr])
            dfs(next, st, vec, viz_target);
        st.push_back(curr);
    }
}

int main(){
    ifstream f("2sat.in");
    ofstream g("2sat.out");

    f >> n >> m;
    for(int i = 0, x, y; i < m; ++i){
        f >> x >> y;
        vec[-x].push_back(y);
        vec[-y].push_back(x);
        inv_vec[x].push_back(-y);
        inv_vec[y].push_back(-x);
    }

    vector<int> st, ord;
    for(int i = -n; i <= n; ++i)
        if(i != 0)
            dfs(i, st, vec, 1);

    for( ; !st.empty(); st.pop_back())
        dfs(st.back(), ord, inv_vec, 0);

    for(auto x : ord)
        if(val[x] == 0)
            val[-x] = 1;
    
    for(int i = -n; i <= n; ++i)
        for(auto j : vec[i])
            if(val[i] == 1 && val[j] == 0){
                g << -1 << '\n';
                return 0;
            }

    for(int i = 1; i <= n; ++i)
        g << val[i] << ' ';

    return 0;
}