1

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

#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 个化合价。我怎样才能做到这一点?

4

1 回答 1

1

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

您需要做的是从所有小于 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

一旦你有了它,一个从这个集合中采样的好方法是使用水库采样

于 2012-09-18T14:47:03.183 回答