Cod sursa(job #1164288)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 1 aprilie 2014 23:19:51
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <cstdio>
#include <vector>
#include <bitset>
#include <algorithm>
#include <stack>
#include <cstring>

#define Nmax 200005

using namespace std;
int N,M,compatible;

vector<int> G[2*Nmax],Gt[2*Nmax];
stack<int> S;
bitset<Nmax>used;
int values[2*Nmax]; /// adica true sau false

int non(int x)
{
    if( x < N) return x + N;
    return x - N;
}

void add_disj(int x,int y)
{
    G[non(x)].push_back(y);
    G[non(y)].push_back(x);

    Gt[y].push_back(non(x));
    Gt[x].push_back(non(y));
}

void read()
{
    scanf("%d%d",&N,&M);
    int x,y;
    for(int i = 1; i <= M; ++i)
    {
        scanf("%d%d",&x,&y);
        if(x < 0)  x = N - x;
        if(y < 0)  y = N - y;
        add_disj(x,y);
    }
}

void DFS(int k)
{
    used[k] = 1;
    for(vector<int>::iterator it = G[k].begin(); it != G[k].end(); ++it)
        if(!used[*it])
            DFS(*it);
    S.push(k);
}

void DFST(int k)
{
    if(values[k] == 1){
        compatible = 0;
        return;
    }
    values[k] = 0;
    values[non(k)] = 1;
    used[k] = 0;
    for(vector<int>::iterator it = Gt[k].begin(); it!= Gt[k].end(); ++it)
        if(used[*it])
            DFST(*it);
}

void kosaraju()
{
    for(int i = 1; i <= 2*N; ++i)
        if(used[i] == 0)
            DFS(i);
    int x;
    while(!S.empty())
    {
        x = S.top();S.pop();
        if(used[x] == 1 && used[non(x)] == 1)
            DFST(x);
    }
}

void solve()
{
    compatible = 1;
    kosaraju();
}

void print()
{
    if(!compatible){
            printf("-1");
        return;
    }
    for(int i = 1; i <= N;++i)
        printf("%d ",values[i]);
}

int main()
{
    freopen("2sat.in","r",stdin);
    freopen("2sat.out","w",stdout);
    read();
    solve();
    print();

    return 0;
}