【问题标题】:Has anyone seen a 2-Sat implementation有没有人见过 2-Sat 实现
【发布时间】:2009-11-14 08:10:33
【问题描述】:

我一直在寻找一段时间,但我似乎无法找到 2-Sat 算法的任何实现。

我正在使用 boost 库(有一个 strongly connected component module)在 c++ 中工作,需要一些指导来创建一个高效的 2-Sat 程序或找到一个现有的库供我通过 c++ 使用。

【问题讨论】:

标签: c++ boost implementation 2-satisfiability


【解决方案1】:

我想您知道如何为 2-Sat 问题建模以使用 SCC 解决它。 我处理 vars 及其否定的方式不是很优雅,但允许一个简短的实现: 给定从0到n-1编号的n个变量,在子句中-i表示变量i的否定,在图中i+n表示相同(我清楚吗?)

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 2022-11-17
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多