Cod sursa(job #1414492)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 2 aprilie 2015 17:43:02
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

const int Nmax = 2 * 100000 + 1;

vector<int> G[Nmax];
vector<int> GT[Nmax];

int solution[Nmax];
int postorder[Nmax];
bool vis[Nmax];
int P;

int N, M;
bool existSolution = true;

int neg(int x)
{
    if (x > N)
        return x - N;
    else
        return x + N;
}

void dfs(int nod)
{
    vis[nod] = 1;

    for (auto x: G[nod])
        if (!vis[x])
            dfs(x);

    postorder[ ++P ] = nod;
}

void dfsT(int nod)
{
    if (solution[nod])
        existSolution = false;

    vis[nod] = false;
    solution[neg(nod)] = 1;

    for (auto x: GT[nod])
        if (vis[x])
            dfsT(x);
}

void SAT()
{
    for (int i = 1; i <= 2 * N; ++i)
        if (!vis[i])
            dfs(i);

    for (int i = P; i >= 1; i--)
    {
        int nod = postorder[i];

        if (vis[nod] && vis[neg(nod)])
            dfsT(nod);
    }
}

int main()
{
    ifstream in("2sat.in");
    ofstream out("2sat.out");

    in >> N >> M;

    for (int i = 1; i <= M; ++i)
    {
        int a, b;
        in >> a >> b;

        if (a < 0) a = -a + N;
        if (b < 0) b = -b + N;

        G[neg(a)].push_back(b);
        G[neg(b)].push_back(a);

        GT[b].push_back(neg(a));
        GT[a].push_back(neg(b));
    }

    SAT();

    if (existSolution)
    {
        for (int i = 1; i <= N; ++i)
            out << solution[i] << " ";

        out << "\n";
    }
    else
        out << "-1\n";

    return 0;
}