简体   繁体   English

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

[英]Adding random edges in a graph generated using BOOST graphical library

I would like to add random edges in my graph, which is as follow: 我想在图形中添加随机边,如下所示:

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

The lines following #1 do that. #1的行可以做到这一点。

But as you can see, there exists 8 edges from each vertex but I Would like to have only 4 to the max and would like to connect all the vertices in a random way and most importantly there can be only 4 valencies from each vertex. 但是正如您所看到的,每个顶点有8个边,但是我想最多只有4个边,并且希望以随机的方式连接所有顶点,最重要的是每个顶点只能有4个价态。 How can I achieve that? 我该如何实现?

EDIT: I said "ordered pair" when I meant "unordered pair"! 编辑:我说“无序对”时说“有序对”! Hope the rephrasing is clearer now. 希望现在的表述更加清晰。

What you need to do is sample without replacement from the set of all unordered pairs of nonnegative integers that are < N. Since it's much easier for a computer to represent an ordered pair than an unordered pair, the usual way to produce this set is to produce all ordered pairs in which the first element is less than the second: 你需要做的是在不脱离集合中的所有无序对非负整数是<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));
    }
}

So eg if N = 4, the set of possible edges to consider is: 因此,例如,如果N = 4,则要考虑的可能边的集合为:

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

A nice way to sample from this set once you have it is to use reservoir sampling . 从该集合中采样的一种好方法是使用储层采样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM