Cod sursa(job #2495286)

Utilizator florin_salamFlorin Salam florin_salam Data 19 noiembrie 2019 01:59:08
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <bitset>

using namespace std;

const int NMAX = 200005;
int n, m;
vector <int> graph[NMAX], revgraph[NMAX];
bitset <NMAX> seen;
int topo[NMAX], topopos;
bool ans[NMAX];
bool bad = false;

inline int neg(int x)
{
    if (x <= n)
        return x + n;
    else
        return x - n;
}

void dfs1(int node)
{
    seen[node] = 1;
    for (auto &x : graph[node])
        if (seen[x] == 0)
            dfs1(x);
    topo[++topopos] = node;
}

void dfs2(int node)
{
    if (ans[node] == true)
        bad = true;
    seen[node] = 1;
    ans[neg(node)] = true;
    for (auto &x : revgraph[node])
        if (seen[x] == 0)
            dfs2(x);
}

int main()
{
    ifstream fin("2sat.in");
    ofstream fout("2sat.out");
    fin >> n >> m;
    for (int i = 1;i <= m;++i)
    {
        int x, y, negx, negy;
        fin >> x >> y;
        if (x < 0)
            x = -x + n;
        if (y < 0)
            y = -y + n;
        negx = neg(x);
        negy = neg(y);
        graph[negx].push_back(y);
        graph[negy].push_back(x);
        revgraph[y].push_back(negx);
        revgraph[x].push_back(negy);
    }
    for (int i = 1;i <= 2 * n;++i)
        if (seen[i] == 0)
            dfs1(i);
    seen.reset();
    for (int i = 2 * n;i >= 1;--i)
        if (seen[topo[i]] == 0 && seen[neg(topo[i])] == 0)
            dfs2(topo[i]);
    if (bad == true)
        fout << "-1\n";
    else
        for (int i = 1;i <= n;++i)
            fout << ans[i] << " ";
    fin.close();
    fout.close();
    return 0;
}