Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 邻接表图表示的实现_C++_Data Structures_Graph Theory - Fatal编程技术网

C++ 邻接表图表示的实现

C++ 邻接表图表示的实现,c++,data-structures,graph-theory,C++,Data Structures,Graph Theory,我刚开始学习图论。我不知道如何使用链表对邻接列表进行编码。例如,如果我有这个图(无向): 我该如何编码?我知道如何使用邻接矩阵,但如何使用邻接列表和链表(c++)进行编码?邻接列表只是一组表示图形边缘的对象 struct edge { node *nodes[2]; edge( node *a, node *b ) { if ( a < b ) { // define canonical order of edges for undirected grap

我刚开始学习图论。我不知道如何使用链表对邻接列表进行编码。例如,如果我有这个图(无向):


我该如何编码?我知道如何使用邻接矩阵,但如何使用邻接列表和链表(c++)进行编码?

邻接列表只是一组表示图形边缘的对象

struct edge {
    node *nodes[2];

    edge( node *a, node *b ) {
        if ( a < b ) { // define canonical order of edges for undirected graph
            nodes[0] = a;
            nodes[1] = b;
        } else {
            nodes[0] = b;
            nodes[1] = a;
        }
    }
};

有很多方法可以做到这一点,如果不知道您打算对图形做什么,很难提出更多建议。

邻接列表只是一个向量/列表数组。图形中的每个元素都是数组中的一个元素,任何边都将添加到其邻接列表中。因此,它看起来像:

struct edge {
    node *nodes[2];

    edge( node *a, node *b ) {
        if ( a < b ) { // define canonical order of edges for undirected graph
            nodes[0] = a;
            nodes[1] = b;
        } else {
            nodes[0] = b;
            nodes[1] = a;
        }
    }
};
struct vertex
{
   //
};

class undirected_graph
{
private:
    std::map<vertex, std::set<vertex>> graph_container;
public:
    void add_vertex(const vertex& v) { //add a vertex to the map }
    void add_edge(const vertex& v, const vertex& u) { //look up vertex in map and add to the vertex adjacency list }
    //Other methods
    //...
 };
A->{B,C}

B->{A,C,D,E}

C->{A,B}

D->{B,E}

E->{B,D}

所以我们从类似于
std::vector
的东西开始。然而,我们可以做得更好,因为垂直是唯一的,因此我们可以利用
映射。此外,顶点只能在边列表中出现一次,因此我们将其修改为
std::map

因此,首先,比如:

struct vertex
{
   //
};

class undirected_graph
{
private:
    std::map<vertex, std::set<vertex>> graph_container;
public:
    void add_vertex(const vertex& v) { //add a vertex to the map }
    void add_edge(const vertex& v, const vertex& u) { //look up vertex in map and add to the vertex adjacency list }
    //Other methods
    //...
 };
struct顶点
{
//
};
类无向图
{
私人:
std::映射图_容器;
公众:
void add_vertex(const vertex&v){//将顶点添加到贴图}
void add_边(常数顶点&v,常数顶点&u){//在地图中查找顶点并添加到顶点邻接列表}
//其他方法
//...
};

From:“在图论中,邻接列表是图形中所有边或弧的列表表示。”您所实现的可能是对其进行了优化,但基本概念有点模糊。@PushkarMishra当然。如果你是第一次尝试实现这一点,请使用最简单的方法。向量是一种有效的选择吗?好的,邻接列表与邻接矩阵的整体观点是,它们对于没有太多边的图来说更节省内存。
map/set
实现可能会更快,但对于任何不是很大的图,差异可能会最小。将std::map用于邻接列表将导致bfs/dfs遍历的复杂性为O(| V |*log(| V |)+| E |),其中| V |,| E |分别是顶点和边的大小。因此,对于稀疏矩阵,它将导致更高的时间复杂度。