图论学习(二)在Boost Graph中返回连通子图序列

来源:互联网 发布:windows arping 编辑:程序博客网 时间:2024/06/05 06:30

参考
http://stackoverflow.com/questions/26763193/return-a-list-of-connected-component-subgraphs-in-boost-graph
本代码实现功能
1.计算连通子图
2.保存子图
3.映射子图和原图的顶点
示例输出如图
这里写图片描述

代码如下

#include <sstream>#include <iostream>#include <boost/graph/subgraph.hpp>#include <boost/graph/adjacency_list.hpp>#include <boost/config.hpp>#include <vector>#include <boost/graph/connected_components.hpp>using namespace std;using namespace boost;// Underlying graph representation and implementation//typedef adjacency_list_traits<vecS, vecS, directedS> Traits;// Graph representationtypedef subgraph< adjacency_list<vecS, vecS, directedS,    property<vertex_color_t, int>, property<edge_index_t, int> > > Graph;// Iterating over vertices and edgestypedef graph_traits<Graph>::vertex_iterator vertex_iter;//typedef graph_traits<Graph>::edge_iterator edge_iter;int main(void){    Graph g;    add_edge(0,1, g);    add_edge(1,4, g);    add_edge(4,0, g);    add_edge(2,5, g);    std::vector<int> comp(num_vertices(g));    int num = connected_components (g, comp.data());    std::cout << std::endl;    std::vector < int >::iterator i;    std::cout << "Total number of components: " << num << std::endl;    for (i = comp.begin(); i != comp.end(); ++i)    std::cout << "Vertex " << i - comp.begin()      << " is in component " << *i << std::endl;      std::vector<Graph* > comps(num);      for(size_t i=0;i<num;++i) {          comps[i] = & g.create_subgraph();      }      for(size_t i=0;i<num_vertices(g);++i) {          cout<<"add vetex "<<i<<"to sub graph "<<comp[i]<<endl;          add_vertex(i, *comps[comp[i]]);      }    pair<vertex_iter, vertex_iter> vip;    cout << "Vertices in g  = [ ";    vip = vertices(g);    for(vertex_iter vi = vip.first; vi != vip.second; ++vi) {        cout << *vi << " ";    }    cout << "]" << endl;    for(size_t i=0;i<num;i++)    {        cout << "Vertices (local) in comps[i]' = [ ";        pair<vertex_iter, vertex_iter> lvip;        lvip = vertices(*comps[i]);        for(vertex_iter vi = lvip.first; vi != lvip.second; ++vi)        {                cout << (*comps[i]).local_to_global(*vi) << " ";        }        cout << "]" << endl;    }    return 0;}
0 0