邻接表之链式前向星

链式前向星比vector邻接表在内存性能和时间性能上更好。

链式前向星用法详见以下模板代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+10;//最大点数
const int maxm=1e6+10;//最大边数
struct node{int to,w,next;}edge[maxm];//边集,to终点,w边权,next同起点的上一条边的编号
int n,m,head[maxn];//输入n个点,m条边
struct Chain_Forward_Star{//链式前向星
    int cnt;
    void init(){//初始化
        cnt=0;
        memset(head,-1,sizeof(head));//初始化为-1
    }
    void add(int u,int v,int w){//加边,u起点,v终点,w边权
        edge[cnt].to=v;
        edge[cnt].w=w;
        edge[cnt].next=head[u];//同样以u为起点的上一条边的编号
        head[u]=cnt++;//更新以u为起点的上一条边的编号
    }
}CFS;
int main()
{
    int u,v,w;
    cin>>n>>m;
    CFS.init();
    for(int i=1;i<=m;i++){
        cin>>u>>v>>w;//u起点,v终点,w边权
        CFS.add(u,v,w);
        //CFS.add(v,u,w);
    }
    for(int i=1;i<=n;i++){
        cout<<i<<endl;
        for(int j=head[i];~j;j=edge[j].next)//倒序遍历以i为起点的边,~j即j!=-1
            cout<<i<<' '<<edge[j].to<<' '<<edge[j].w<<endl;
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/HOLLAY/p/11517722.html