[数据结构]链式前向星详解
3.7____链式前向星(链接为参考博客)
什么是前向星?
前向星是一种特殊的边集数组,我们把边集数组中的每一条边按照起点从小到大排序,如果起点相同就按照终点从小到大排序
用len[i]表示,所有以i为起点的边的数量。
用head[i]表示,以i为起点的边集在排序后第一次出现的位置。
以下图为例,我们建立前向星表
我们输入边的顺序为:
1 2
2 3
3 4
1 3
4 1
1 5
4 5
那么排完序后就得到:
排序后编号 : 1 2 3 4 5 6 7
_____起点u: 1 1 1 2 3 4 4
_____终点v: 2 3 5 3 4 1 5
得到:
head[1] = 1 len[1] = 3
head[2] = 4 len[2] = 1
head[3] = 5 len[3] = 1
head[4] = 6 len[4] = 2
链式前向星数据结构定义以及加边函数为
struct Edge
{
int next;
int to;
int w;
}Edge[N];
head[N];
/// idx 为边的编号,初值为0;
/// a为起点,b为终点,dis为两点之间的距离(边权)
void add(int a,int b,int dis)
{
edge[idx].w = dis;
edge[idx].to = b;
edge[idx].next = head[a];
head[a] = idx++;
}
可以试试手动写一遍这个代码,我在学习的时候,写到next之后我就突然明白了这个结构了
next表示对于顶点a的链路,最后一个节点的位置
to表示这表边的终点
w表示这条边的边权
head表示,顶点a最后加上的边的编号
head[]数组一般初始化为-1
现在我们还是按照上面的图和输入来模拟一下:
edge[0].to = 2; edge[0].next = -1; head[1] = 0;
edge[1].to = 3; edge[1].next = -1; head[2] = 1;
edge[2].to = 4; edge[2],next = -1; head[3] = 2;
edge[3].to = 3; edge[3].next = 0; head[1] = 3;
edge[4].to = 1; edge[4].next = -1; head[4] = 4;
edge[5].to = 5; edge[5].next = 3; head[1] = 5;
edge[6].to = 5; edge[6].next = 4; head[4] = 6;
对于边的遍历,采用以下方式
for(int i = 1 ; i <= n ; i++){
for(int j = h[i] ; j != -1 ; j = ne[j]){
...
}
}

浙公网安备 33010602011771号