Cod sursa(job #2054717)

Utilizator RaduMirceaAndreiRadu Mircea Andrei RaduMirceaAndrei Data 2 noiembrie 2017 14:08:27
Problema 2SAT Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
# include <fstream>
# include <vector>
# include <stack>
# define DIM 100010
using namespace std;
ifstream fin("2sat.in");
ofstream fout("2sat.out");
stack<int> s;
vector<int> Lista[DIM];
int Marcat[DIM],niv[DIM],low[DIM],viz[DIM];
int n,m,sol,k,x,y,i,j,ok;
int rv(int x){
    if(x>n)
        return x-n;
    else
        return x+n;
}
void tarjan(int nc){
    if(ok)
        return;
    k++;
    niv[nc]=low[nc]=k;
    s.push(nc);
    for(int i=0;i<Lista[nc].size();i++){
        int nv=Lista[nc][i];
        if(!niv[nv])
            tarjan(nv);
        if(!viz[nv])
            low[nc]=min(low[nc],low[nv]);
    }
    if(low[nc]==niv[nc]){
        sol++;
        while(s.top()!=nc){
            int nv=s.top();
            Marcat[nv]=1;
            if(((viz[nv]||viz[rv(nv)])&&(!viz[nc]))||(((!viz[nv])||(!viz[rv(nv)]))&&viz[nc])){
                fout<<"-1\n";
                ok=1;
                return;
            }
            if(!viz[nc]){
                viz[nv]=1;
                viz[rv(nv)]=2;
            }
            s.pop();
        }
        s.pop();
        Marcat[nc]=1;
        if(viz[nc]&&(!viz[rv(nc)])){
            fout<<"-1\n";
            ok=1;
            return;
        }
        if(!viz[nc]){
            viz[nc]=1;
            viz[rv(nc)]=2;
        }
    }
}
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;
        Lista[rv(x)].push_back(y);
        Lista[rv(y)].push_back(x);
    }
    for(i=1;i<=2*n;i++){
        if(!niv[i])
            tarjan(i);
        if(ok)
            return 0;
    }
    for(i=1;i<=n;i++)
        fout<<viz[i]%2<<" ";
    fout<<"\n";
    return 0;
}