【学习笔记】链式前向星

public_sickle / 2024-01-26 / 原文

链式前向星,是一种邻接表存图的方式。本质上是用数组模拟一个链表。
适合存各种类型的图,但是查询两节点间的边是否存在很不方便,对出边进行排序也很麻烦。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N=1e5+5;
typedef struct Edge{
	int to,next,val;
} edge;
int h[N],n,m,idx=0;
edge g[N];
bool vis[N];
void add(int u,int v,int w){
	idx++;  //新增一条边
	g[idx].next=h[u];
	g[idx].to=v;
	g[idx].val=w;  //相当于链表的头插法
	h[u]=idx;      //将表头设为这条边
}
int main(){
    ios::sync_with_stdio(false);
    memset(h,-1,sizeof(h));
    memset(vis,false,sizeof(vis));
    cin>>n>>m;
    for(int i=1;i<=m;i++){
		int u,v,w;
		cin>>u>>v>>w;
		add(u,v,w);
	}
    return 0;
}