邻接表建图

http://blog.csdn.net/lvshubao1314/article/details/22987925

向前星建图:前向星也是一种通过存储边的信息的方式存储图的数据结构。它的构造方式非常简单,读入每条边的信息,将边存放在数组中,把数组中的边按照起点顺序排序,前向星就构造完成了。链接:http://blog.csdn.net/lvshubao1314/article/details/22958683

#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;
}

链式向前星:http://blog.csdn.net/lvshubao1314/article/details/22990455

 C++  STL 里有一个vector容器可以代替邻接表进行建图,二者有异曲同工之妙。

具体用法请听课或自学STL

博客1:http://blog.itpub.net/14466241/viewspace-755183/

博客2:http://blog.sina.com.cn/s/blog_9f1c0931010180cy.html

posted @ 2016-09-28 19:50  a_clown_cz  阅读(211)  评论(0)    收藏  举报