[英]C graph adjacency list implementation growing neighbour array
我找到了一個實現,並且正在遍歷代碼,對我來說一部分似乎還不清楚。
struct graph {
int n; /* number of vertices */
int m; /* number of edges */
struct successors {
int d; /* number of successors */
int len; /* number of slots in array */
char is_sorted; /* true if list is already sorted */
int list[1]; /* actual list of successors */
} *alist[1];
};
在graph_add_edge函數中
/* do we need to grow the list? */
while (g->alist[u]->d >= g->alist[u]->len) {
g->alist[u]->len *= 2;
g->alist[u] =
realloc(g->alist[u],
sizeof(struct successors) + sizeof(int) * (g->alist[u]->len - 1));
}
為什么長度必須加倍? 為什么甚至需要它? 為下一個項目騰出空間是否總是d + 1(后繼人數+ 1)?
因為在每次需要更多內存而不是將大小加1時,將CPU大小加倍就更省錢了。
在后一種情況realloc
將被稱為用於每個新加入的邊緣,並且realloc
是相當昂貴的。 想象一下,您有128條邊: realloc
將被調用128次,但是如果您每次將大小加倍,它將僅被調用7 = log2(128)
次。
此外realloc
最有可能是更慢的原始存儲部分越長,因為realloc
將舊存儲部緩沖器潛在復制到新的較大的一個,和較長的部分,不再拷貝將采取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.