Cod sursa(job #2542470)

Utilizator mihneacazCazacu Mihnea mihneacaz Data 10 februarie 2020 01:00:24
Problema 2SAT Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

const int NMAX = 2 * 1e5 + 5;

ifstream cin ("2sat.in");
ofstream cout ("2sat.out");

int n, m;
vector <int> g1[NMAX];
vector <int> g2[NMAX];
bool viz[NMAX];
vector <int> nodes;
vector <int> ctc[NMAX];
int comp[NMAX];
int val[NMAX];

int notn(int a)
{
    if(a <= n)
        return a + n;
    else
        return a - n;
}

void dfs1(int node)
{
    viz[node] = 1;
    for(auto x: g1[node]) {
        if(viz[x] == 0) {
            dfs1(x);
        }
    }
    nodes.push_back(node);
}
vector <int> sortaret;
void dfs2(int node, int cnt)
{
    viz[node] = 1;
    ctc[cnt].push_back(node);
    comp[node] = cnt;
    for(auto x: g2[node]) {
        if(viz[x] == 0) {
            dfs2(x, cnt);
        }
    }
    sortaret.push_back(node);
}

int main() {
    cin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        int x, y;
        cin >> x >> y;
        if (x < 0) x = abs(x);
        else x += n;
        if (y < 0) y = abs(y);
        else y += n;
        g1[notn(x)].push_back(y);
        g1[notn(y)].push_back(x);
//        cout << notn(x) << ' ' << y << endl;
//        cout << notn(y) << ' ' << x << endl;
        g2[y].push_back(notn(x));
        g2[x].push_back(notn(y));
    }
    for(int i = 1; i <= 2 * n; ++i) {
        if(viz[i] == 0) {
            dfs1(i);
        }
    }
    reverse(nodes.begin(), nodes.end());
    for(int i = 0; i <= 2 * n; ++i)
        viz[i] = 0;
    int cnt = 0;
    for(auto x: nodes) {
        if(viz[x] == 0) {
            ++cnt;
            dfs2(x, cnt);
        }
    }
    for(int i = 1; i <= 2 * n; ++i)
        val[i] = -1;
    reverse(sortaret.begin(), sortaret.end());
    for(auto x: sortaret) {
//        cout << x << " ";
        if(val[notn(x)] != -1) {
            val[x] = 1 - val[notn(x)];
        } else {
            val[x] = 0;
        }
    }
//    cout << "\n";
    for(int i = 1; i <= n; ++i) {
        cout << val[i] << " ";
    }
    cout << "\n";
    return 0;
}