图的存储结构三部曲 ——其一:前向星

来源:互联网 发布:淘宝买家订单怎么导出 编辑:程序博客网 时间:2024/05/20 12:48

前向星也是一种通过存储边的信息的方式存储图的数据结构。它的构造方式非常简单,读入每条边的信息,将边存放在数组中,把数组中的边按照起点顺序排序,前向星就构造完成了。为了查询方便,经常会有一个数组存储起点为Vi的第一条边的位置。

所需数据结构如下:

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;int head[10005];//存储起点为Vi的第一条边的位置struct note{    int from,to,w;//起点,终点,权值};bool cmp(note a,note b){    if(a.from==b.from&&a.to==b.to)          return a.w<b.w;    if(a.from==b.from)          return a.to<b.to;    return a.from<b.from;}note edge[10005];int main(){     int n,m;     cin >> n>> m;     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)//确定起点为Vi的第一条边的位置              head[edge[i].from]=i;       }       int k;       for(int i=1;i<=n;i++)       {           for(k=head[i];edge[k].from==i&&k<m;k++)           {               cout << edge[k].from<<" " << edge[k].to<<" "<< edge[k].w<<endl;           }       }       return 0;}


0 0
原创粉丝点击