快速建图模板
图是一种重要的数据结构,在算法中有着广泛地运用。快速地建图,能够帮助我们更好地进行算法实现。本文介绍一种基于连接静态链表,采用头插法的方式进行快速建图的模板。以下是核心代码部分:
#include <iostream>
#define maxn 1010
#define maxm 500010
using namespace std;
int tot = 0; // edge 中有多少条边
int head[maxn]; // 表头数组
struct Edge
{
int to; // 此节点的数
int next; // 此节点指向的下一个节点,这里采用的是静态数组的方式,所以使用的是int,而不是指针
int c; // 权重
}edge[maxm]; // 静态数组,这样避免了要进行空间的申请和释放
/**
* 添加从 from -> to 的边
* @param from 起始边
* @param to 终止边
* @c 权重值 / 边权
*/
void add(int from,int to,int c)
{
++tot; // (tot++)相当于申请了一个新的节点,只是上面是采用静态数组代替new的方式,所以,直接用(++tot)就行了,不需要像指针方式new空间了
edge[tot].to = to;
edge[tot].next = head[from];
edge[tot].c = c;
head[from] = tot; // 这一步可能比较难理解,看下面的图帮助理解吧
}
- 执行两次
add(int from, int to, int c)
函数 add(1,3,1)
添加一个由 1->3,边权是1的边add(1,4,1)
添加一个由 1->4,边权是1的边
edge[1].to = 3; 该节点的数据信息 //edge[++tot].to=to;
edge[1].next = head[1]; 和fron指向同一个节点 // edge[tot].next=head[from];
edge[1].c = 1; 边权赋值 // edge[tot].c=c;
head[1] = 1; 头节点指向新建的这个节点 // head[from]=tot;
edge[2].to = 4; 该节点的数据信息 //edge[++tot].to=to;
edge[2].next = head[1]; 和fron指向同一个节点 // edge[tot].next=head[from];
edge[2].c = 1; 边权赋值 // edge[tot].c=c;
head[1] = 2; 头节点指向新建的这个节点 // head[from]=tot;