通常我們對於圖論的實現是用鄰接矩陣實現的,雖然很方便,結果也很直觀,但如果數據量比較大,耗費的資源就非常多了。所以我們會用鄰接表來對圖中的信息,雖然讀取相關信息時比鄰接矩陣複雜,但存儲的容量小,只需要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;
}