拓扑排序算法

拓扑排序是很重要的算法,使用boost库的topological_sort。

使用如下,输入数据:

{
  "edge_list": [
    [0, 1],
    [2, 4],
    [2, 5],
    [0, 3],
    [1, 4],
    [4, 3]
    ]
}

输出拓扑排序数据如下:

{
  "topo_order": [
    2,
    5,
    0,
    1,
    4,
    3
  ]
}

集成到可视化平台如下:

其中boost库demo如下:

#include <boost/config.hpp>
#include <iostream>
#include <list>
#include <algorithm>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>
#include <iterator>
#include <utility>

typedef std::pair< std::size_t, std::size_t > Pair;

/*
  Sample output:

  A topological ordering: 2 5 0 1 4 3

*/

int main(int, char*[])
{
    // begin
    using namespace boost;

    /* Topological sort will need to color the graph.  Here we use an
       internal decorator, so we "property" the color to the graph.
       */
    typedef adjacency_list< vecS, vecS, directedS,
        property< vertex_color_t, default_color_type > >
        Graph;

    typedef boost::graph_traits< Graph >::vertex_descriptor Vertex;
    Pair edges[6] = { Pair(0, 1), Pair(2, 4), Pair(2, 5), Pair(0, 3),
        Pair(1, 4), Pair(4, 3) };

    Graph G(6);
    for (std::size_t j = 0; j < 6; ++j)
        add_edge(edges[j].first, edges[j].second, G);


    boost::property_map< Graph, vertex_index_t >::type id
        = get(vertex_index, G);

    typedef std::vector< Vertex > container;
    container c;
    topological_sort(G, std::back_inserter(c));

    std::cout << "A topological ordering: ";
    for (container::reverse_iterator ii = c.rbegin(); ii != c.rend(); ++ii)
        std::cout << id[*ii] << " ";
    std::cout << std::endl;

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值