存图的三种方式
邻接矩阵
空间复杂度过高
1 2 3 4 5 6 7 8 9 10 11 12
| #include<bits/stdc++.h> const int V = 1000; int mat[maxn][maxn]; int main() { int i,j,w; memset(mat, 0, sizeof(mat)); scanf("%d%d%d",&i,&j,&w); mat[i][j] = w; mat[i][j] = 0; printf("%d",mat[i][j]); }
|
邻接表
内存利用率较高,但重边不好处理
1 2 3 4 5 6 7 8 9 10 11 12
| #include<vector> using namespace std; const int V = 100000; vector<int> e[V]; e[i].clear(); e[i].push_back(j); e[i][0]; for (int j=0; j<(int)e[i].size(); ++j) { if (e[i][j] == k) { ...... } }
|
数组模拟邻接表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| #include<bits/stdc++.h> using namespace std; const int N = 1010, M = 1010; int h[N], e[M], w[M], nxt[M], eidx; void add(int u, int v, int weight){ e[eidx] = v; w[eidx] = weight; nxt[eidx] = h[u]; h[u] = eidx; eidx++; } void iterate(int u){ for(int eid = h[u]; eid != -1; eid = nxt[eid]){ int v = e[eid]; int weight = w[eid]; cout << u << "->" << v << ", weight: " << weight << endl; } } int main() { int n, m; cin >> n >> m; memset(h, -1, sizeof h); eidx = 0; while(m--){ int u, v, weight; cin >> u >> v >> weight; add(u, v, weight); } for(int u = 1; u <= n; ++u) iterate(u); return 0; }
|
链式前向星
内存利用率高,不像vector实现的邻接表有爆内存的风险,但重边不好处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const int maxn = 10005; int head[maxn], cnt=0; struct Edge{ int to; int w; int next; }Edge edge[maxn]; void add(int u,int v,int w){ edge[cnt].w = w; edge[cnt].to = v; edge[cnt].next = head[u]; head[u] = cnt++; } int main() { for(int i=0; i<=n; i++) for(int j=head[i]; j!=-1; j=edge[j].next){ ...... } }
|