关于【链式前向星】的自学理解

我们就以下图为例:


根据建边的顺序,我们可以给这些边都创建一个序号,如:

1 2      <---1号
2 3      <---2号
3 4      <---3号
1 3      <---4号
4 1      <---5号
1 5      <---6号
4 5      <---7号

按照《算法竞赛》中给出的思路,我们可以写出链表:

1 -> 5 -> 3 -> 2
2 -> 3
3 -> 4
4 -> 5 -> 1
5

这样,我们可以从后往前地观察,维护一个head[i]数组,表示输入边中的弧头为i的最后一条边的编号,即:

head[1] = 6
head[2] = 2
head[3] = 3
head[4] = 7
head[5] = 0(即不存在弧头为5的边)

我们在存边的时候也可以顺便维护to[i]数组,即第i条边的弧尾。这个太简单了,就不说了。

最后我们维护next[i]数组,我们设第i条边的弧头为x,则next[i]表示在第i条边之前最后一条弧头为x的边的编号,即:

next[1] = 0
next[2] = 0
next[3] = 0
next[4] = 1
next[5] = 0
next[6] = 4
next[7] = 5

拿到这三个数组后,我们就可以实现加边操作。

void AddEdge (int u, int v, int x) {
	to[++ cnt] = v;
	w[cnt] = x;
	next[cnt] = head[u];
	head[u] = cnt;
}

当我们要枚举这个点的邻接点时,只需用for循环遍历即可。

for (int i = head[x]; i; i = next[i]) {
	//...
}

例题:邻接表存储带权的无向图

代码

#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;

const int MAXN = 1000 + 5;
int n, m, u, p, x, cnt, to[MAXN], head[MAXN], w[MAXN], next[MAXN];

struct node {
	int x, w;
	bool operator < (const node x) const {
		if (w == x.w) {
			return this->x < x.x;
		} else {
			return w < x.w;
		}
	}
};

vector <node> v;

void AddEdge (int u, int v, int x) {
	to[++ cnt] = v;
	w[cnt] = x;
	next[cnt] = head[u];
	head[u] = cnt;
}

int main () {
	scanf ("%d %d", &n, &m);
	for (int i = 1; i <= m; i ++) {
		scanf ("%d %d %d", &u, &p, &x);
		AddEdge (u, p, x);
		AddEdge (p, u, x);
	}
	for (int i = 1; i <= n; i ++) {
		v.clear();
		for (int j = head[i]; j; j = next[j]) {
			v.push_back((node) {to[j], w[j]});
		}
		sort (v.begin(), v.end());
		for (int i = 0; i < v.size(); i ++) {
			printf ("%d ", v[i].x);
		}
		printf ("\n");
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前向星和链式前向星的区别在于实现方式和数据结构的不同。 前向星是一种存储图的边的数据结构,它使用两个数组来存储边的信息。一个数组存储每个顶点的第一条边的索引,另一个数组存储每条边的下一条边的索引。这种方式可以方便地遍历每个顶点的所有边。 链式前向星是一种基于链表的存储方式,它使用链表来存储每个顶点的边。每个顶点都有一个指向第一条边的指针,每条边都有一个指向下一条边的指针。这种方式可以动态地添加和删除边。 总结来说,前向星使用数组存储边的信息,链式前向星使用链表存储边的信息。链式前向星相比前向星更加灵活,可以方便地进行边的插入和删除操作。但是链式前向星的空间复杂度较高,因为需要额外的指针来存储链表的连接关系。 引用\[1\]中提到,链式前向星的整体结构很像邻接表,但是实现方式不同。链式前向星的思想和邻接表一致,只是在实现上有所区别。因此,链式前向星的使用和邻接表相一致,可以用于存储和遍历图的边的信息。 #### 引用[.reference_title] - *1* *2* *3* [链式前向星](https://blog.csdn.net/MuShan_bit/article/details/123882339)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值