在使用 BOOST 图形库生成的图形中添加随机边

Adding random edges in a graph generated using BOOST graphical library

本文关键字:图形 添加 随机 BOOST 图形库      更新时间:2023-10-16

我想在我的图中添加随机边缘,如下所示:

#include <iostream>
#include <utility>                   // for std::pair
#include <algorithm> 
#include <boost/graph/adjacency_list.hpp>
#include "boost/graph/topological_sort.hpp"
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/graphviz.hpp>
int main()
{
    using namespace std;
    using namespace boost;
    typedef adjacency_list< listS, vecS, undirectedS > undigraph;
    int const N = read_int_from_user("Number of vertices: ");   
    undigraph g(N);
    // add some edges,             // #1
    for (int i = 0; i != N; ++i)
    {
        for (int j = 0; j != N; ++j)
        {
            add_edge(i, j, g);
        }
    }
    write_graphviz(cout, g);
}

#1后面的行就是这样做的。

但如您所见,每个顶点有

8 条边,但我希望最多只有 4 条,并希望以随机方式连接所有顶点,最重要的是每个顶点只能有 4 条价。我怎样才能做到这一点?

编辑:当我的意思是"无序对"时,我说"有序对"! 希望改写现在更清楚。

您需要做的是从 N <的所有>无序非负整数对的集合中进行采样,而无需替换。 由于计算机表示有序对比表示无序对容易得多,因此生成此集合的常用方法是生成第一个元素小于第二个元素的所有有序对:

vector<pair<int, int> > pairs;
for (int i = 0; i < N; ++i) {
    for (int j = i + 1; j < N; ++j) {
        pairs.push_back(make_pair(i, j));
    }
}

因此,例如,如果N = 4,则要考虑的可能边集为:

0, 1
0, 2
0, 3
1, 2
1, 3
2, 3

一旦有了这个集合,一个很好的方法是使用水库采样。