鄰接矩陣和鄰接表
阿新 • • 發佈:2021-08-28
鄰接矩陣和鄰接表
鄰接矩陣:
優點:簡單清楚,適合小圖
缺點:矩陣中許多空值,浪費記憶體,點多邊少避免使用
// 帶權有向圖
int mp[maxn][maxn];
for(int i = 0; i < n; i++) {
int u, v, cost;
cin >> u >> v >> cost;
mp[a][b] = cost;
}
例子:
其對應的矩陣是:
1 | 2 | 3 | 4 | |
---|---|---|---|---|
1 | 1 | |||
2 | 1 | |||
3 | 1 | 1 | ||
4 | 1 |
m[i][j]
表示從i
點到j
點有邊,其值則是該邊的權值。
鄰接表
優點:記憶體消耗小,容易找到直接連線到特定頂點的所有連結。
struct node { int to; // 終點 int cost; // 權值 } // 帶權有向圖 vector<node> a[maxn]; for(int i = 0; i < n; i++) { int u, v, cost; cin >> u >> v >> cost; a[u].push_back({v, cost}); } int s = a[u].size(); // 表示點 u 的出度 // 遍歷 尋找 u 到 v 的邊 for(int i = 0; i < a[u].size(); i++) { if(a[u][i] == v) { cout << "Yes" << endl; } }
例子:
其對應的矩陣是: