动态添加到图形数据结构中
Dynamically adding to a graph data structure
让我首先声明,我只想要方向,而不一定是实际的代码,除非一个小片段是理解这一点的唯一方法。
我需要使用C++中的邻接列表或矩阵创建一个DIRECTED图数据结构,并从标准输入中添加顶点/边,这意味着动态。
我想如果我能够先实例化一组顶点,然后创建边并将其添加到图中,我就能很好地创建一个图,但我不明白如何添加一条包含尚未实例化的顶点的边。
例如,标准输入的第一行显示:
迈阿密->纽约/1100->华盛顿/1000->阿尔伯克基/1700
如果纽约顶点还没有添加到图中,我应该如何添加从迈阿密到纽约的边?
谢谢大家的指导!
如何添加一条边包含一个尚未实例化的顶点。
简单:实例化它..
我认为这没有任何问题。假设V
是迄今为止看到的顶点集。CCD_ 2最初是空的。当您读取输入x->y
时,您会得到它的端点(x
和y
)。如果其中任何一个未实例化(即,不在V
中),则实例化它并将其添加到顶点集。
另一种方法是:假设我们通过图的边集E
来定义图。根据定义,任何边都是一对顶点,这对顶点又定义了图的顶点集。
每次出现新的唯一节点时,如何调整邻接列表的大小?您可以维护一组唯一的节点值,并在每次添加节点时使用其大小来调整邻接列表的大小。下面是一些执行相同操作的代码。
class Graph
{
public:
// Add links in the graph
void addLink(int id1, int id2){
// Add to hashset
uniqueNodes.insert(id1);
uniqueNodes.insert(id2);
// Resize on the adjacency list based on how many nodes exists in the uniqueNodes set
adjList.resize(uniqueNodes.size());
// Make the connections assuming undirected graph
adjList[id1].push_back(id2);
adjList[id2].push_back(id1);
}
// Print the graph
void printGraph(){
for(int i = 0; i < adjList.size(); i++){
cout << i << ":";
for(auto it = adjList[i].begin(); it != adjList[i].end(); it++)
cout << *it << "->";
cout << "NULLn";
}
}
private:
// Adjacency list for the graph
vector<list<int>> adjList;
// Hashset to help define the size of the adjacency list as nodes come in
set<int> uniqueNodes;
};
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- C++中deque数据结构的大O是什么?
- 适合大型图形的数据结构
- 如何编写递归函数来计算图形数据结构中的最短路径
- 动态添加到图形数据结构中
- 是否有标准的图形数据结构可用于基准测试?
- 一个c++图形数据结构的并发垃圾收集
- 图形数据结构内存管理