【发布时间】:2015-03-14 16:08:45
【问题描述】:
我目前拥有的是这样的:
void addEdge(listNode **adjacencyList, int firstVertex, int secondVertex, int cost) {
if (firstVertex == secondVertex) return;
attachNeighbor(firstVertex, cost, adjacencyList[secondVertex]);
attachNeighbor(secondVertex, cost, adjacencyList[firstVertex]);
}
void attachNeighbor(int id, int cost, listNode *root) {
if (root->vertex == 0) {
root->vertex = id;
root->cost = cost;
} else {
listNode *neighbor;
neighbor = (listNode *) malloc(sizeof(listNode));
neighbor->cost = cost;
neighbor->vertex = id;
listNode *next = root;
while (next->next != NULL) {
next = next->next;
}
next->next = neighbor;
}
}
然而,有 10k+ 个顶点和超过 100 万条边,它真的很慢,因为每个插入操作都需要 O(邻居数)。后来我要做的只是遍历所有邻居一次,所以我不需要快速检索。我考虑过双向链表并保持指向最后一个节点的指针,然后当我必须迭代时,我会倒退,但我不知道如何在 C 中做到这一点
【问题讨论】:
标签: c optimization data-structures time-complexity graph-theory