数据结构-图-存储
邻接矩阵
存储如下图1,图2
图1
对应邻接矩阵
图2
#include<bits/stdc++.h>
#define MAXN 1005
using namespace std;
int n;
int v[MAXN][MAXN];
int main(){cin>>n;for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){cin>>v[i][j];}}for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){if(v[i][j]>0){cout<<"edge from point "<<i<<" to point "<<j<<" with length "<<v[i][j]<<"\n"; }} }return 0;
}
运行效果:
邻接表
存储示例代码:
#include<bits/stdc++.h>
#define MAXN 1005
using namespace std;
struct edge{int to,cost;
};
int n,m;
vector<edge> p[MAXN];
int v[MAXN][MAXN];
int main(){cin>>n>>m;for(int i=1;i<=m;i++){int u,v,l;cin>>u>>v>>l;p[u].push_back((edge){v,l});}for(int i=1;i<=n;i++){for(int j=0;j<p[i].size();j++){v[i][p[i][j].to]=p[i][j].cost;}}for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){cout<<v[i][j]<<' ';}cout<<"\n";}return 0;
}
运行效果