Hat jemand eine 2-SAT-Implementierung gesehen?
-
20-09-2019 - |
Frage
Ich habe eine Weile gesucht, aber ich kann einfach keine Implementierung des 2-SAT-Algorithmus finden.
Ich arbeite in C ++ mit der Boost -Bibliothek (die a hat stark verbundenes Komponentenmodul) und benötigen eine Anleitung, um entweder ein effizientes 2-SAT-Programm zu erstellen oder eine vorhandene Bibliothek für mich über C ++ zu finden.
Lösung
Ich nehme an, Sie wissen, wie man ein 2-SAT-Problem modelliert, um es mit SCC zu lösen. Die Art und Weise, wie ich Vars und seine Negation bewältige, ist nicht sehr elegant, ermöglicht jedoch eine kurze Implementierung: Angegebene N -Variablen von 0 bis n -1, in den Klauseln -bedeutet die Negation der Variablen I und im Diagramm i+n bedeutet das gleiche (bin ich klar?)
#include <boost/config.hpp>
#include <iostream>
#include <vector>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/foreach.hpp>
typedef std::pair<int, int> clause;
//Properties of our graph. By default oriented graph
typedef boost::adjacency_list<> Graph;
const int nb_vars = 5;
int var_to_node(int var)
{
if(var < 0)
return (-var + nb_vars);
else
return var;
}
int main(int argc, char ** argv)
{
std::vector<clause> clauses;
clauses.push_back(clause(1,2));
clauses.push_back(clause(2,-4));
clauses.push_back(clause(1,4));
clauses.push_back(clause(1,3));
clauses.push_back(clause(-2,4));
//Creates a graph with twice as many nodes as variables
Graph g(nb_vars * 2);
//Let's add all the edges
BOOST_FOREACH(clause c, clauses)
{
int v1 = c.first;
int v2 = c.second;
boost::add_edge(
var_to_node(-v1),
var_to_node(v2),
g);
boost::add_edge(
var_to_node(-v2),
var_to_node(v1),
g);
}
// Every node will belong to a strongly connected component
std::vector<int> component(num_vertices(g));
std::cout << strong_components(g, &component[0]) << std::endl;
// Let's check if there is variable having it's negation
// in the same SCC
bool satisfied = true;
for(int i=0; i<nb_vars; i++)
{
if(component[i] == component[i+nb_vars])
satisfied = false;
}
if(satisfied)
std::cout << "Satisfied!" << std::endl;
else
std::cout << "Not satisfied!" << std::endl;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow