如何从图中随机选择一个顶点?

时间:2016-07-28 23:52:23

标签: c++ random graph

我正在寻找使用c ++从图中随机选取数字的解决方案。
例如,我有一个图形,在两个顶点之间添加边(一个或多个),我如何随机选择一个数字? 一些代码:

#include <iostream>
#include <list>
#include <queue>

using namespace std;
// Graph class represents a undirected graph using adjacency list representation
class Graph
{
private:
    int V; // # of vertices
    list<int> *adj;  // Pointer to an array containing adjacency lists
public:
    Graph(int V)  // Constructor
    {
        this->V = V;
        adj = new list<int>[V];
    }
    void addEdge(int v, int w); // function to add an edge to graph
    void print(int v, int w); //function to display 
    };

void Graph::addEdge(int v, int w)
{
    adj[v].push_front(w); // Add w to v’s list.
    adj[w].push_front(v); // Add v to w’s list.
    print(v, w);

}

void Graph::print(int v, int w) {
cout << v << " - " << w << endl;}

主要:

Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);


样本输出:

  

0 - 1
0 - 2
1 - 3

2 个答案:

答案 0 :(得分:0)

使用math lib。兰德功能。选择随机数并从边列表中选择(0到边数-1),然后选择另一个随机数并选择边的顶点,0或1(边缘的顶部/顶部顶点)

答案 1 :(得分:0)

#include <stdlib.h> 
#include <iostream>
#include <list>
#include <queue>

using namespace std;
// Graph class represents a undirected graph using adjacency list representation
class Graph
{
private:
    int V; // # of vertices
    list<int> *adj;  // Pointer to an array containing adjacency lists
public:
    Graph(int V)  // Constructor
    {
        this->V = V;
        adj = new list<int>[V];
    }
    void addEdge(int v, int w); // function to add an edge to graph
    void print(int v, int w); //function to display 
    };

void Graph::addEdge(int v, int w)
{
    adj[v].push_front(w); // Add w to v’s list.
    adj[w].push_front(v); // Add v to w’s list.
    print(v, w);

}

int Graph::getRandomVertexFromEdge()
{
    int list_size_divided_by_2 = adj.size() / 2;
    int rEdge = (rand() % list_size_divided_by_2);
    int rVW = (rand() % 1);
    int ret = adj[(rEdge + rVW)];
    //this will return a random vertex from a random edge;
    print(rEdge,rVW);
    return ret;
}

void Graph::print(int v, int w) {
cout << v << " - " << w << endl;}