nxpp
Header-only graph utilities on top of Boost Graph Library
Loading...
Searching...
No Matches
sat.hpp
Go to the documentation of this file.
1#pragma once
2
11#include <boost/graph/adjacency_list.hpp>
12#include <boost/graph/strong_components.hpp>
13#include <stdexcept>
14#include <utility>
15#include <vector>
16
17namespace nxpp {
18
21inline int to_2sat_vertex_id(int literal) {
22 if (literal == 0) {
23 throw std::invalid_argument("Literal 0 is not valid in 2-SAT");
24 }
25 return (literal > 0) ? (2 * literal - 2) : (-2 * literal - 1);
26}
27
34inline bool two_sat_satisfiable(int num_variables, const std::vector<std::pair<int, int>>& clauses) {
35 using SatGraph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>;
36
37 SatGraph g(2 * num_variables);
38 for (const auto& [x, y] : clauses) {
39 boost::add_edge(to_2sat_vertex_id(-x), to_2sat_vertex_id(y), g);
40 boost::add_edge(to_2sat_vertex_id(-y), to_2sat_vertex_id(x), g);
41 }
42
43 std::vector<int> comp(boost::num_vertices(g));
44 boost::strong_components(g, boost::make_iterator_property_map(comp.begin(), boost::get(boost::vertex_index, g)));
45
46 for (int i = 1; i <= num_variables; ++i) {
47 if (comp[to_2sat_vertex_id(i)] == comp[to_2sat_vertex_id(-i)]) {
48 return false;
49 }
50 }
51 return true;
52}
53
54} // namespace nxpp
bool two_sat_satisfiable(int num_variables, const std::vector< std::pair< int, int > > &clauses)
Returns whether a 2-SAT instance is satisfiable.
Definition sat.hpp:34
int to_2sat_vertex_id(int literal)
Converts a signed 2-SAT literal into the internal implication-graph vertex ID. Throws std::invalid_ar...
Definition sat.hpp:21