三種鄰接表存圖模板:vector鄰接表、數組鄰接表、鏈式前向星


vector鄰接表:

const int maxn=1e5+10;

struct Edge{
    int u,v,w;
    Edge(int _u=0,int _v=0,int _w=0){u=_u,v=_v,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);
}

遍歷某個鏈表的方法: for(int i=0;i<G[u].size();i++) 

最喜歡這種寫法,寫起來快,也非常好理解。

 

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){u=_u,v=_v,w=_w;}
    Edge(Edge &e){u=e.u,v=e.v,w=e.w;}
};
Edge E[maxm];
int head[maxn],next[maxm],ne;
void init()
{
    ne=0;
    memset(head,0,sizeof(head));
}
void addedge(int u,int v,int w)
{
    E[++ne]=Edge(u,v,w);
    next[ne]=head[u];
    head[u]=ne;
}

遍歷某個鏈表的方法: for(int i=head[u];i;i=next[i]) 

在題目卡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,0,sizeof(head));
}
void addedge(int u,int v,int w)
{
    ++ne;
    E[ne].u=u, E[ne].v=v, E[ne].w=w;
    E[ne].next=head[u];
    head[u]=ne;
}

把數組鄰接表的next數組扔到Edge結構體里保存,就變成了鏈式前向星……所以,鏈式前向星其實就是鄰接表。

遍歷某個鏈表的方法: for(int i=head[u];i;i=E[i].next) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM