图的存储

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int INF = 0x7fffffff;
const int maxn = 1100;
struct Edge {
    int from, to, dist;
};

vector<Edge> edges;
vector<int> G[maxn];//类似邻接表,保存着边的编号。

void init() {
   for(int i = 0; i < maxn; i++) G[i].clear();//节点从1开始编号。
   edges.clear();
}

void AddEdge(int from, int to, int dist) {
    int m;
    edges.push_back((Edge){from, to, dist});
    m = edges.size();//edges
    G[from].push_back(m-1);//给每个边编号从0开始。
}

void output(int u)
{
    for(int i = 0; i < (int)G[u].size(); i++) {
        Edge& e = edges[G[u][i]];//值得借鉴。
        printf("%d -> %d = %d
", e.from, e.to, e.dist);
    }
}

int main()
{
    int n;
    while(scanf("%d", &n) != EOF) {//the number of the edges;
        init();
        for(int i = 0; i < n; i++) {//n个顶点,编号1 ~ n
            int from, to, dist;
            scanf("%d%d%d", &from, &to, &dist);
            AddEdge(from, to, dist);
            AddEdge(to, from, dist);
        }
        for(int i = 1; i <= n; i++) {
            output(i);
        }
    }
    return 0;
}

/****
6
1 2 2
1 4 3
2 4 4
2 3 5
3 4 6
3 5 7
****/


原文地址:https://www.cnblogs.com/pangblog/p/3260348.html