Cod sursa(job #1957768)

Utilizator tudi98Cozma Tudor tudi98 Data 7 aprilie 2017 19:14:03
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>
using namespace std;

#define PER(i,a) for (int i = a - 1; i >= 0; i--)
#define REP(i,a) for (int i = 0; i < a; i++)
#define FOR(i,a,b) for (int i = a; i <= b; i++)
#define ROF(i,a,b) for (int i = a; i >= b; i--)
#define FOREACH(it,x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)
#define all(x) (x).begin(),(x).end()
#define ll long long
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define pii pair<int,int>
#define SZ(x) ((int)(x).size())

int N,M;
vector<int> G[200001];

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

bool in_stack[200001];
int low[200001],id[200001],ID = 0;
stack<int> S;
int comp[200001];
int SCC = 0;
int val[200001];

void Fail() {
    puts("-1");
    exit(0);
}

void tarjan(int node)
{
    ++ID; S.push(node); in_stack[node] = 1;
    low[node] = id[node] = ID;

    FOREACH(it,G[node]) {
        if (id[*it] == 0) {
            tarjan(*it);
            low[node] = min(low[node],low[*it]);
        }
        else if (in_stack[*it]) low[node] = min(low[node],id[*it]);
    }

    if (id[node] == low[node]) {
        int u; ++SCC;
        do {
            u = S.top(); in_stack[u] = 0;
            S.pop(); comp[u] = SCC; if (comp[non(u)] == SCC) Fail();
            if (val[u] == 0) val[u] = 1, val[non(u)] = -1;
        } while (u != node);
    }
}

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

    scanf("%d %d",&N,&M);
    while (M--)
    {
        int x,y; scanf("%d%d",&x,&y);
        if (x < 0) x = N - x;
        if (y < 0) y = N - y;
        G[non(x)].pb(y);
        G[non(y)].pb(x);
    }

    FOR(i,1,2*N) if (id[i] == 0) tarjan(i);

    FOR(i,1,N) printf("%d ",(val[i]==1));
}