链式前向星
作用
- 储存图中边的数据结构。
举例
由如下图,需要将其关系进行储存
储存关系如下:
解释如下:
-
head[i]表示以i为起点的第一条边
-
int to; //这条边的终点 int w; //权值 int next; //兄弟边
结构如下
- 定义边的结构体
- 将边加入前向星中
- 遍历前向星
边的结构体
struct EDGE{
int to; //这条边的终点
int w; //权值
int next; //兄弟边
};
EDGE edge[MAXM];
加边方法
void addEdge(int u, int v, int w) { //起点u, 终点v, 权值w
edge[++cnt].next = head[u]; // next 定义起点u, 终点v的边还有哪些
edge[cnt].w = w;
edge[cnt].to = v;
head[u] = cnt; //cnt为边的编号。head[u] = cnt表示,起点u的最新的边为编号为cnt的边。
}
遍历
从节点编号为st的节点开始,遍历其所有的子节点。
for (int i = head[st]; i != 0; i = edge[i].next) {
cout << "Start: " << st << endl;
cout << "End: " << edge[i].to << endl;
cout << "W: " << edge[i].w << endl << endl;
}
完整代码
#include <iostream>
using namespace std;
#define MAXM 500010
#define MAXN 10010
struct EDGE{
int to; //这条边的终点
int w; //权值
int next; //兄弟边
};
EDGE edge[MAXM];
int n, m, cnt;
int head[MAXN]; //head[i]表示以i为起点的第一条边
void addEdge(int u, int v, int w) { //起点u, 终点v, 权值w
edge[++cnt].next = head[u]; // next 定义起点u, 终点v的边还有哪些
edge[cnt].w = w;
edge[cnt].to = v;
head[u] = cnt; //cnt为边的编号。head[u] = cnt表示,起点u的最新的边为编号为cnt的边。
}
void Print() {
//i开始为第一条边,每次指向下一条(以0为结束标志)若下标从0开始,next应初始化-1
for (int st = 1; st <= n; st++)//n个起点
for (int i = head[st]; i != 0; i = edge[i].next) {
cout << "Start: " << st << endl;
cout << "End: " << edge[i].to << endl;
cout << "W: " << edge[i].w << endl << endl;
}
}
int main() {
int s, t, w;
cin >> n >> m;
for(int i=1; i<=m; i++) {
cin >> s >> t >> w;
addEdge(s, t, w);
}
Print();
return 0;
}
/*
5 7
1 2 1
2 3 2
3 4 3
1 3 4
4 1 5
1 5 6
4 5 7
*/