문제

나는 한동안 찾고 있었지만 2-SAT 알고리즘의 구현을 찾을 수없는 것 같습니다.

나는 부스트 라이브러리와 함께 C ++에서 일하고 있습니다 ( 강력하게 연결된 구성 요소 모듈) 효율적인 2-SAT 프로그램을 만들거나 C ++를 통해 활용할 기존 라이브러리를 찾으려면 약간의 지침이 필요합니다.

도움이 되었습니까?

해결책

SCC로 해결하기 위해 2-SAT 문제를 모델링하는 방법을 알고 있다고 생각합니다. 내가 VARS와 그 부정을 처리하는 방식은 매우 우아하지는 않지만 짧은 구현을 허용합니다. 0에서 N -1까지 번호가 매겨진 n 변수, 클로스에서 i는 변수 i의 부정을 의미합니다. 같은 의미입니다 (내가 분명합니까?)

#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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top