Cod sursa(job #1778266)

Utilizator alexandra_udristoiuUdristoiu Alexandra Maria alexandra_udristoiu Data 13 octombrie 2016 17:35:13
Problema 2SAT Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include<fstream>
#include<vector>
#include<stack>
#define DIM 100005
using namespace std;
int n, m, x, y, i, j, nr, cnt;
int f[DIM], viz[DIM], ctc[DIM], niv[DIM], low[DIM], sol[DIM], ff[DIM];
vector<int> v[DIM], w[DIM];
stack<int> s;
ifstream fin("2sat.in");
ofstream fout("2sat.out");
int inv(int x){
    if(x <= n){
        return x + n;
    }
    return x - n;
}
void dfs(int nod){
    viz[nod] = f[nod] = 1;
    s.push(nod);
    cnt++;
    low[nod] = niv[nod] = cnt;
    for(int i = 0; i < v[nod].size(); i++){
        int vecin = v[nod][i];
        if(viz[vecin] == 0){
            dfs(vecin);
        }
        if(f[vecin] == 1){
            low[nod] = min(low[nod], low[vecin]);
        }
    }
    if(low[nod] == niv[nod]){
        nr++;
        int x;
        do{
            x = s.top();
            ctc[x] = nr;
            f[x] = 0;
            w[nr].push_back(x);
            s.pop();
        }while(x != nod);
    }
}
int main(){
    fin>> n >> m;
    for(i = 1; i <= m; i++){
        fin>> x >> y;
        if(x < 0){
            x = n - x;
        }
        if(y < 0){
            y = n - y;
        }
        v[ inv(x) ].push_back(y);
        v[ inv(y)].push_back(x);
    }
    for(i = 1; i <= 2 * n; i++){
        if(viz[i] == 0){
            dfs(i);
        }
    }
    for(i = 1; i <= nr; i++){
        if(ff[i] == 1){
            continue;
        }
        for(j = 0; j < w[i].size(); j++){
            x = w[i][j];
            if(ctc[x] == ctc[ inv(x) ] ){
                fout<<"-1\n";
                return 0;
            }
            ff[ ctc[ inv(x)] ] = 1;
            sol[x] = 1;
            sol[ inv(x) ] = 0;
        }
    }
    for(i = 1; i <= n; i++){
        fout<< sol[i] <<" ";
    }
    return 0;
}