存图(vector邻接表、邻接矩阵、链式前向星)
除了特殊情况必须使用特定的存储方式,遵循以下优先级
链式前向星 > vector邻接表 > 邻接矩阵
临界矩阵
邻接矩阵就是用一个二维数组表示两个点之间的关系。
例如点u到点v有权值为w的单项边,则设 mp[u][v] = w;
便可以通过获取 mp[][] 的值知道两点是否有边,边权为多少
这种存储方式会占用很多不必要的内存空间
vector邻接表
#include<bits/stdc++.h>
using namespace std;
struct Edge {
int v, w;
};
vector<Edge>mp[10000];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int u, v, w;
cin >> u >> v >> w;
mp[u].push_back({ v, w });
}
}
链式前向星
存储每个点的头部,通过头插法的方式连接,然后找到头部依次向下遍历
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 100000;
// 创建边结构
struct E{
int v, w, next;
// 下一个点,边权,当前边的上一个边
}Edge[MAXN];
int tot, head[MAXN];
// 建边
void AddEdge(int u, int v, int w) {
Edge[tot].v = v;
Edge[tot].w = w;
Edge[tot].next = head[u];
head[u] = tot++;
}
int main() {
// 初始化head
memset(head, -1, sizeof(head));
// 建边
int t; cin >> t;
for (int i = 0; i < t; i++) {
int u, v, w;
cin >> u >> v >> w;
AddEdge(u, v, w);
}
// 遍历 u 连接的所有边
int u; cin >> u;
for (int i = head[u]; ~i; i = Edge[i].next) {
cout << Edge[i].v << " " << Edge[i].w << endl;
}
}