Cod sursa(job #2693937)

Utilizator trifangrobertRobert Trifan trifangrobert Data 7 ianuarie 2021 17:00:57
Problema 2SAT Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <bitset>

using namespace std;

const int NMAX = 100000;
int N, M;
vector <vector <int>> graph, revgraph;
bitset <2 * NMAX> seen;
vector <int> topo;
vector <bool> answer;

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

void AddEdge(int x, int y){
    if (x < 0)
        x = -x + N;
    if (y < 0)
        y = -y + N;
    --x; --y;
    int 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);
}

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

bool bad;

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

int main(){
    ifstream fin("2sat.in");
    ofstream fout("2sat.out");
    fin >> N >> M;
    graph = vector <vector <int>>(2 * N, vector <int>());
    revgraph = vector <vector <int>>(2 * N, vector <int>());
    answer = vector <bool>(2 * N, false);
    for (int i = 0;i < M;++i){
        int x, y;
        fin >> x >> y;
        AddEdge(x, y);
    }
    for (int i = 0;i < 2 * N;++i){
        if (seen[i] == 0)
            dfs1(i);
    }
    reverse(topo.begin(), topo.end());
    for (auto& i : topo){
        if (seen[i] == 1 && seen[neg(i)] == 1)
            dfs2(i);
    }
    if (bad){
        fout << -1 << "\n";
    }
    else {
        for (int i = 0;i < N;++i)
            fout << answer[i] << " ";
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}