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 <utility>
14#include <vector>
15
16namespace nxpp {
17
19inline int to_2sat_vertex_id(int literal) {
20 return (literal > 0) ? (2 * literal - 2) : (-2 * literal - 1);
21}
22
29inline bool two_sat_satisfiable(int num_variables, const std::vector<std::pair<int, int>>& clauses) {
30 using SatGraph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>;
31
32 SatGraph g(2 * num_variables);
33 for (const auto& [x, y] : clauses) {
34 boost::add_edge(to_2sat_vertex_id(-x), to_2sat_vertex_id(y), g);
35 boost::add_edge(to_2sat_vertex_id(-y), to_2sat_vertex_id(x), g);
36 }
37
38 std::vector<int> comp(boost::num_vertices(g));
39 boost::strong_components(g, boost::make_iterator_property_map(comp.begin(), boost::get(boost::vertex_index, g)));
40
41 for (int i = 1; i <= num_variables; ++i) {
42 if (comp[to_2sat_vertex_id(i)] == comp[to_2sat_vertex_id(-i)]) {
43 return false;
44 }
45 }
46 return true;
47}
48
49} // 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:29
int to_2sat_vertex_id(int literal)
Converts a signed 2-SAT literal into the internal implication-graph vertex ID.
Definition sat.hpp:19