Cod sursa(job #2239051)

Utilizator mariusn01Marius Nicoli mariusn01 Data 8 septembrie 2018 19:21:16
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>
#include <set>
#define DIM 100010
using namespace std;

vector<int> L[2*DIM];

ifstream fin("2sat.in");
ofstream fout("2sat.out");
bitset<2*DIM> IS, v;
int low[DIM*2], niv[DIM*2], w[DIM*2];

stack<int> s;
set<int> R;

int n, m, g, i, x, y, sol;

void dfs(int nod) {
    v[nod] = 1;
    s.push(nod);
    IS[nod] = 1;
    g++;
    niv[nod] = low[nod] = g;
    int x;
    for (int i=0; i<L[nod].size(); i++) {
        x = L[nod][i];
        if (!v[x]) {
            dfs(x);
            low[nod] = min(low[nod], low[x]);
        } else
            if (IS[x])
                low[nod] = min(low[nod], low[x]);
    }
    if (low[nod] == niv[nod]) {
        R.clear();
        do {
            x = s.top();
            s.pop();
            IS[x] = 0;

            if ((x<=n && R.find(x+n) != R.end()) || (x>n && R.find(x-n) != R.end()))
                sol = -1;
            R.insert(x);
            if (w[x] == 0) {
                w[x] = 1;
                if (x <= n)
                    w[x+n] = -1;
                else
                    w[x-n] = -1;
            }
        } while (x!=nod);
    }

}

int main() {
    fin>>n>>m;
    for (i=1;i<=m;i++) {
        fin>>x>>y;

        if (x > 0) {
            if (y > 0) {
                L[x+n].push_back(y);
                L[y+n].push_back(x);
            } else {
                L[x+n].push_back(-y+n);
                L[-y].push_back(x);
            }
        } else {
            if (y > 0) {
                L[-x].push_back(y);
                L[y+n].push_back(-x+n);
            } else {
                L[-x].push_back(-y+n);
                L[-y].push_back(-x+n);
            }
        }
    }

    for (i=1;i<=2*n;i++)
        if (!v[i])
            dfs(i);

    if (sol == -1)
        fout<<sol<<"\n";
    else
        for (i=1;i<=n;i++)
            fout<<(w[i] == 1 ? 1 : 0)<<" ";

    return 0;
}