![用邻接表或vector实现存边以及具体如何调用[模板] 用邻接表或vector实现存边以及具体如何调用[模板]](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700)
存边;
对于指针实现的邻接表:
struct edge{
int from,next,to,w;
}E[maxn];
int head[maxn],tot=0;//head初始化为-1;
void add(int x,int y,int z){
E[++tot].from=x;//头结点
E[tot].to=y;//连接的下一个结点
E[tot].w=z;//边权值
E[tot].next=head[x];//连接指针
head[x]=tot;//指针指向tot,即可通过head[x]为下标,运用E
}
对于vector:
#include <cstdio>
#include <vector>
struct edge{
int v,w;
edge(int _v,int _w){
v=_v;w=_w;
}
};
vector <edge> g[maxn];
void add(int x,int y,int z){
g[x].push_back(edge(y,z));
}
具体调用:
比如我们在spfa里需要找到u,连接的所有的边;
邻接表:
void use(int x){
int u=x;//x为头结点;
for(int i=head[u];i!=-1;i=E[i].next){
v=E[i].to; }
}
vector:
void use(int x){
int ans=g[x].size();
for(int i=0;i<ans;i++){
int v=g[x][i].v; }
}
注意vector是从0开始存的;
总的来说还是vector比较好用,但是自己太弱> <,有时候不太会用stl,所以还是要小心~~