0

我想使用 boost 库生成一个图形,该库允许用户输入边和顶点的数量。我基本上想做的是,

  1. 我希望用户输入顶点数和每个顶点的编号。
  2. 我会给用户一个特权,可以使用数字作为参考来选择一个顶点作为主顶点。
  3. 我希望用户在控制台中指定每个顶点的边数,并且边可以是随机的。

是否有可能使用 BGL 以某种方式实现这一点?如果是这样,一个例子将是一个很好的开始。

预先感谢一吨,

干杯!!

4

1 回答 1

2

假设您知道 a) 基本 C++ 和 b) 基本 BGL,这里有一个简单的算法来构建具有给定顶点价数的随机无向图:

  1. 读取所需顶点的数量;叫它N。我们有顶点集[0, N)

  2. 对于每个iin [0, N),读取所需的化合价v[i](例如存储在容器中,例如 a std::vector<int>)。

  3. 现在有趣的部分:迭代每个顶点并尽可能多地添加随机边。这是一些类似 C++ 的伪代码,有空白供您填写。

    for (i = 0; i != N; ++i)
    {
        if (i + 1 == N && v[i] > 0)
        {
            Error: The user input was impossible to satisfy
            Abort program
        }
    
        while (v[i] > 0)
        {
            pick a random j in [i + 1, N)
    
            if (v[j] > 0)
            {
                Add edge i <-> j
                --v[i];
                --v[j];
            }
        }
    }
    
    If we haven't aborted, we now have a random graph.
    

如果您想扩展其中的任何部分,请发表评论。


更新:这是一个示例实现。会有差距;这只是一个大纲。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>

int read_int(std::string const & initmsg, std::string const & repeatmsg)
{
    std::cout << initmsg;

    for (std::string line; std::getline(std::cin, line); )
    {
        std::istringstream iss(line);
        int res;

        if (iss >> res >> std::ws && iss.get() == EOF) { return res; }

        std::cout << repeatmsg;
    }

    std::cerr << "Unexpected end of input! Aborting.\n";
    std::exit(1);
}

std::string read_string(std::string const & msg)
{
    std::string res;
    std::cout << msg;

    if (std::getline(std::cin, res)) { return res; }

    std::cerr << "Unexpected end of input! Aborting.\n";
    std::exit(1);
}

int main()
{
    int const N = read_int("Number of vertices: ",
                           "I did not understand, try again. Number of vertices: ");

    std::vector<unsigned int> valencies;
    std::vector<std::string> vertex_names;

    valencies.reserve(N);
    vertex_names.reserve(N);

    for (int i = 0; i != N; ++i)
    {
        std::string const msg1 = "Enter valency for vertex " + std::to_string(i) + ": ";
        std::string const msg2 = "Enter description for vertex " + std::to_string(i) + ": ";
        std::string const rep = "Sorry, say again: ";

        valencies.push_back(read_int(msg1, rep));
        vertex_names.push_back(read_string(msg2));
    }

    for (int i = 0; i != N; ++i)
    {
        std::cout << "Vertex " << i << " (\"" << vertex_names[i]
                  << "\") has valency " << valencies[i] << std::endl;
    }

    // Now run the above algorithm!
}
于 2012-09-16T19:23:56.583 回答