链式前向星

/*
edge[边号].to   =     当前边顶点的位置
edge[边号].next =     上一个以u为起点的边的编号
head[起点]      =     当前编号/边号 (最后保存的是以i为起点的边中编号最大的那条边)
*/

#include <bits/stdc++.h>
using namespace std;
const int maxn = 110; //最大顶点数

//构建边结构体
struct Edge{
    int next;   //连接同一顶点的下一条边
    int to;     //边的终点
    int w;      //边权
}edge[maxn*maxn];  //边集

int head[maxn]; //顶点表
int cnt; //计数

//建立邻接表
void add(int u, int v, int w)
{
    edge[cnt].w = w;
    edge[cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}

int main()
{
    int n, m;
    scanf("%d%d", &n, &m);
    cnt = 0;
    //首先将顶点表初始化,他最开始每一个都没有下一条边
    for(int i = 1; i <= n; i++) head[i] = -1; //v start from 1

    for(int i = 0; i < m; i++){
        int a, b, w;
        scanf("%d%d%d", &a, &b, &w);
        add(a, b, w);
    }

    //对于每一个顶点
    for(int u = 1; u <= n; u++){
        printf("%d -->", u);
        //遍历它所有的边
        for(int i=head[u];~i;i=edge[i].next){
            printf("  %d", edge[i].to);
        }printf("\n");
    }
    return 0;
}
/*
5 7
1 2 1
2 3 1
3 4 1
1 3 1
4 1 1
1 5 1
4 5 1
*/
posted @ 2019-02-20 17:52  sourcry  阅读(135)  评论(0)    收藏  举报