圖的鄰接表表示法

通常我們對於圖論的實現是用鄰接矩陣實現的,雖然很方便,結果也很直觀,但如果數據量比較大,耗費的資源就非常多了。所以我們會用鄰接表來對圖中的信息,雖然讀取相關信息時比鄰接矩陣複雜,但存儲的容量小,只需要O(|V|+|E|)的內存空間。

如用c++實現的鄰接表的存儲:

#include <iostream>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
using namespace std;

const int maxn = 1000;
vector<int> G[maxn];

int main()
{
    int V, E;
    scanf("%d%d", &V, &E);
    for(int i = 0; i < E; i++)
    {
        int s, t;
        scanf("%d%d", &s, &t);
        G[s].push_back(t);
    }
    return 0;
}
發佈了59 篇原創文章 · 獲贊 45 · 訪問量 55萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章