1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| struct Edge{ int from_; int to_; int weight_; };
struct Graph{
Graph(int nc, int ec) :nodeCount_{nc} ,edgeCount_{ec} {} int AddEdge(int from, int to, int weight = 0) { const auto id = id_++; next_[id] = head_[from]; head_[from] = id; edges_[id] = Edge{from, to, weight}; return id; } int AddUndirectedEdge(int from, int to, int weight = 0) { const auto id1 = AddEdge(from, to, weight); const auto id2 = AddEdge(to, from, weight); return id1; } template<typename Func> void ForEachEdgeOfNode(int node, Func func) { for(int id = head_[node]; id >= 0; id = next_[id]) { func(id, edges_[id]); } } void Print() const { for(int eid = 0; eid < id_; ++eid) { const auto& edge = edges_[eid]; std::printf("(%d,%d,%d)\n", edge.from_, edge.to_, edge.weight_); } } int id_ = 0; const int nodeCount_; const int edgeCount_; std::vector<int> head_ = std::vector<int>(nodeCount_, -1); std::vector<int> next_ = std::vector<int>(edgeCount_, -1); std::vector<Edge> edges_ = std::vector<Edge>(edgeCount_); };
|