1. 图的存储方法有
1.1 边的集合法,记录节点数、边数,每条边的起点和终点。这是最简单最基本的方法。但是这种方法寻找邻居点比较麻烦,需要转成邻接矩阵或者数组模拟邻接表
#include<bits/stdc++.h>
using namespace std;
#define N 1000
int n; //点的数量
int m; //边的数量
struct edge
{
int u,v,w; //边的起点终、点和权值
};
struct edge e[N]; //边的集合
int main()
{
return 0;
}
1.2 邻接矩阵(二维数组),其记录任意两点之间是否有边,简单容易理解,但是有很多冗余数据 ,时间复杂度高,适合存储稠密图
#include<bits/stdc++.h>
using namespace std;
#define N 1000
int n; //点的数量
int m; //边的数量
int u,v,w; //边的起点终、点和权值
int a[N][N]; //邻接矩阵,初始值全为0
int main()
{
cin>>n>>m;
for(int i=n;i<=m;i++)
{
cin>>u>>v>>w;
a[u][v]=w;
a[v][u]=w; //无向图
}
return 0;
}
1.3 数组模拟邻接表,其只记录存有边的两点,不容易理解,但无冗余数据,时间复杂度低,适合存储稀疏图
#include<bits/stdc++.h>
using namespace std;
#define N 1000
int n; //点的数量
int m; //边的数量
struct edge
{
int v,w; //边的终点和权值
};
vector<edge> G[N]; //动态数组存储图
void insert(int u,int v,int w)
{
G[u].push_back({v,w});
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y,z; //边的起点、终点和权值
cin>>x>>y>>z;
insert(x,y,z);
insert(y,x,z); //无向图需要建两条边
}
return 0;
}
1.3.1 方法一:普通数组实现
1.3.2 方法二:动态数组实现