转载

三种邻接表存图模板:vector邻接表、数组邻接表、链式前向星

vector邻接表:

复制代码
const int maxn=1e5+10;

struct Edge{
    int u,v,w;
    Edge(int u=0,int v=0,int w=0){this->u=u,this->v=v,this->w=w;}
};
vector<Edge> E;
vector<int> G[maxn];
void init(int l,int r)
{
    E.clear();
    for(int i=l;i<=r;i++) G[i].clear();
}
void addedge(int u,int v,int w)
{
    E.push_back(Edge(u,v,w));
    G[u].push_back(E.size()-1);
}
复制代码

最喜欢这种写法,写起来快,也非常好理解。

 

vector邻接表还有一种魔性写法:

复制代码
const int maxn=1e5+10;

struct Edge{
    int u,v,w;
    Edge(int u=0,int v=0,int w=0){this->u=u,this->v=v,this->w=w;}
};
vector<Edge> E[maxn];
void init(int l,int r){for(int i=l;i<=r;i++) E[i].clear();}
void addedge(int u,int v,int w){E[u].push_back(Edge(u,v,w));}
复制代码

其实差不多……属于懒人中的懒人写法。

 

数组邻接表:

复制代码
const int maxn=1e5+10;
const int maxm=1e5+10;

struct Edge{
    int u,v,w;
    Edge(int u=0,int v=0,int w=0){this->u=u,this->v=v,this->w=w;}
    Edge(Edge &e){this->u=e.u,this->v=e.v,this->w=e.w;}
};
Edge E[maxm];
int head[maxn],next[maxm],ne;
void init()
{
    ne=0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int w)
{
    E[ne]=Edge(u,v,w);
    next[ne]=head[u];
    head[u]=ne++;
}
复制代码

在题目卡vector时可以使用,如果include了STL库,可能next数组会产生ambiguous,需要改个名字或者改用链式前向星(如下)。

 

链式前向星:

复制代码
const int maxn=1e5+10;
const int maxm=1e5+10;

struct Edge{
    int u,v,w;
    int next;
};
Edge E[maxm];
int head[maxn],ne;
void init()
{
    ne=0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int w)
{
    E[ne].u=u, E[ne].v=v, E[ne].w=w;
    E[ne].next=head[u];
    head[u]=ne++;
}
复制代码

把数组邻接表的next数组扔到Edge结构体里保存,就变成了链式前向星……所以,链式前向星其实就是邻接表。

转载请注明出处: https://dilthey.cnblogs.com/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值