Cod sursa(job #1212499)

Utilizator mariusn01Marius Nicoli mariusn01 Data 24 iulie 2014 22:20:55
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.39 kb
#include <fstream>
#include <vector>
#include <stack>
#include <set>
#define DIM 100010

using namespace std;
ifstream fin("2sat.in");
ofstream fout("2sat.out");

stack<int> S;
set<int> R;
vector<int> L[2*DIM];

int A[2*DIM], v[2*DIM], IS[2*DIM], low[2*DIM], niv[2*DIM];

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

void dfs(int nod) {
    g++;
    low[nod] = g;
    niv[nod] = g;
    IS[nod] = 1;
    S.push(nod);
    for (int i=0; i<L[nod].size(); i++) {
        if (niv[L[nod][i]] == 0) {
            dfs(L[nod][i]);
            low[nod] = min( low[nod], low[L[nod][i]] );
        } else
            if (IS[L[nod][i]]) {
                low[nod] = min( low[nod], low[L[nod][i]] );
            }
    }

    if (low[nod] == niv[nod]) {
        R.clear();
        do {
            x = S.top();

            //fout<<x<<" ";

            IS[x] = 0;
            S.pop();
            if ((x <= n && R.find(n+x) != R.end()) || (x > n && R.find(x-n)!= R.end())) {
                sol = -1;
            }
            R.insert(x);
            if (A[x] == 0) {
                A[x] = 1;
                v[x] = 1;
                if (x <= n) {
                    /*
                    if (A[x+n] == 1)
                        sol = -1;
                    */
                    v[x+n] = 0;
                    A[x+n] = 1;
                } else {
                    /*
                    if (A[x-n] == 1)
                        sol = -1;
                    */
                    v[x-n] = 0;
                    A[x-n] = 1;
                }
            }
        } while (x!=nod);
        //fout<<"\n";
    }

}

int main() {

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

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

    for (i=1;i<=n;i++)
        if (A[i] == 0)
            dfs(i);
    if (sol == -1) {
        fout<<sol;
        return 0;
    }

    for (i=1;i<=n;i++)
        fout<<v[i]<<" ";

    return 0;
}