写在最前:笔者其实对链式前向星的理解并不是很深刻,老是忘记怎么写,每次都要看模板。而最近的一次,模板出现了问题。于是,记录下正确的写法。
所用如下:
数组
h
e
a
d
[
i
]
head[i]
head[i] 大小为点的数量
h
e
a
d
[
i
]
head[i]
head[i]:最后一条起点为i的边的序号
变量
e
_
c
n
t
e\_cnt
e_cnt 最终大小(加边操作全部结束后)为边的数量
e
_
c
n
t
e\_cnt
e_cnt:维护每条边的序号
结构体
e
[
i
]
{
t
o
,
n
e
x
t
,
w
e
i
g
h
t
}
e[i] \left\{to,next,weight \right\}
e[i]{to,next,weight} 大小为边的数量
e
[
i
]
.
t
o
e[i].to
e[i].to:编号为i的边的终点
e
[
i
]
.
n
e
x
t
e[i].next
e[i].next:起点与编号为i的边相同的上一条边
e
[
i
]
.
w
e
i
g
h
t
e[i].weight
e[i].weight:编号为i的边的权值
c
o
d
e
code
code 存储:
void add_edge(int u,int v,int w{
e[++e_cnt].next=head[u];
e[e_cnt].to=v;
e[e_cnt].weight=w;
head[u]=e_cnt;
return;
}
c o d e code code 遍历:
for(int i=head[s];i;i=e[i].next{
int to=e[i].to;
......
//s就是初始的点。
//比如某个dfs程序为void dfs(int now,int from),则s就是now
}
附 实际使用中的一份代码:
inline void get_sum(int now,int fro){
sum[now]=tim[now];
for(reg int i=he[now];i;i=e[i].nxt){
int to=e[i].to;
if(to==fro)continue;
get_sum(to,now);
sum[now]+=sum[to];
}
return;
}