繁体   English   中英

如何从图中随机选取顶点?

[英]How to randomly pick a vertices from 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

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

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

暂无
暂无

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

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