邻接表建图
邻接表的思想:
- 将同一个起点的边放在一个链表里面,也就是说对于一个有n个节点的图,我们需要维护n个这样节点的链表;
- 用n个指针,分别指向以节点i为起点的第一条边touzhizhen,也可以理解成(1)中所述的链表的头指针。
参考实现1(指针方式)
struct edge
{
int to;
edge *next;
};
edge *head[n];
void addEdge(int x,int y)
{
edge *p;
p=new node;
p->to=y;
p->next=head[x];
head[x]=p;
return;
}
参考实现2(数组方式)
struct edge
{
int to;
int next;
}graph[m];
int head[n];
int tot=0;
void addEdge(int x,int y)
{
graph[++tot].to=y;
graph[tot].next=head[x];
head[x]=tot;
return;
}
树是一种特殊的图,因此也可以用邻接表的方式来存储树的结构。我们可以把树的每一条边,看成是从其父节点指向其子节点的一条有向边。
参考实现3(多数组无结构方式)
int tot=0;
int head[n];
int to[m];
int next[m];
int father[n];
void addEdge(int fa,int son)
{
to[++tot]=son;
father[son]=fa;
next[tot]=head[fa];
head[fa]=tot;
return;
}