前向星
前向星是一种通过储存边信息的方式储存图的结构。
基本方法
- 读入每条边的信息(起点、终点、权值)
- 存放在数组里
- 按照起点排序
- 通常会有一个head数组,记录每个起点上的第一条边
代码实现
- 声明
int head[maxn];
struct node{
int from,to,w;
} edge[maxn];
- 排序函数
bool cmp(node a,node b){
if(a.from==b.from){
if(a.to==b.to)
return a.w<b.w;
return a.to<b.to;
}
return a.from<b.from;
}
- 读入数据
cin>>m//the number of edge
for(int i=0;i<m;i++){
cin>>edge[i].from>>edge[i].to>>edge[i].w;
}
sort(edge,edge+m,cmp);
memset(head,-1,sizeof(head));
head[edge[0].from]=0;
for(int i=1;i<m;i++){
if(edge[i].from!=edge[i-1].from)
head[edge[i].from]=i;
}
- 遍历
cin>>n;//the number of vertex
for(int i=0;i<n;i++){
for(int k=head[i];edge[k].from==i&&k<m;k++){
cout<<edge[k].from<<" "<<edge[k].to<<" "<<edge[k].w<<endl;
}
}
复杂度说明
- 时间复杂度
- 空间复杂度
优点
- 点多的情况有优势
- 可以储存重边
缺点
- 排序浪费时间
- 无法直接判断两个点之间是否有边