-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.h
92 lines (72 loc) · 2.67 KB
/
graph.h
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#pragma once
#include <cstdlib>
#include <vector>
#include "ranges.h"
namespace graph {
using VertexId = size_t;
using EdgeId = size_t;
template <typename Weight>
struct Edge {
VertexId from;
VertexId to;
Weight weight;
};
template <typename Weight>
class DirectedWeightedGraph {
public:
using IncidenceList = std::vector<EdgeId>;
using IncidentEdgesRange = ranges::Range<typename IncidenceList::const_iterator>;
DirectedWeightedGraph() = default;
explicit DirectedWeightedGraph(size_t vertex_count);
explicit DirectedWeightedGraph(std::vector<Edge<Weight>> edges, std::vector<IncidenceList> incidence_lists);
EdgeId AddEdge(const Edge<Weight>& edge);
size_t GetVertexCount() const;
size_t GetEdgeCount() const;
const Edge<Weight>& GetEdge(EdgeId edge_id) const;
IncidentEdgesRange GetIncidentEdges(VertexId vertex) const;
const std::vector<Edge<Weight>>& GetEdges() const;
const std::vector<IncidenceList>& GetIncidenceLists() const;
private:
std::vector<Edge<Weight>> edges_;
std::vector<IncidenceList> incidence_lists_;
};
template <typename Weight>
DirectedWeightedGraph<Weight>::DirectedWeightedGraph(size_t vertex_count) : incidence_lists_(vertex_count) {}
template <typename Weight>
DirectedWeightedGraph<Weight>::DirectedWeightedGraph(std::vector<Edge<Weight>> edges,
std::vector<IncidenceList> incidence_lists)
: edges_(std::move(edges)), incidence_lists_(std::move(incidence_lists)) {}
template <typename Weight>
EdgeId DirectedWeightedGraph<Weight>::AddEdge(const Edge<Weight>& edge) {
edges_.push_back(edge);
const EdgeId id = edges_.size() - 1;
incidence_lists_.at(edge.from).push_back(id);
return id;
}
template <typename Weight>
size_t DirectedWeightedGraph<Weight>::GetVertexCount() const {
return incidence_lists_.size();
}
template <typename Weight>
size_t DirectedWeightedGraph<Weight>::GetEdgeCount() const {
return edges_.size();
}
template <typename Weight>
const Edge<Weight>& DirectedWeightedGraph<Weight>::GetEdge(EdgeId edge_id) const {
return edges_.at(edge_id);
}
template <typename Weight>
typename DirectedWeightedGraph<Weight>::IncidentEdgesRange DirectedWeightedGraph<Weight>::GetIncidentEdges(
VertexId vertex) const {
return ranges::AsRange(incidence_lists_.at(vertex));
}
template <typename Weight>
const std::vector<Edge<Weight>>& DirectedWeightedGraph<Weight>::GetEdges() const {
return edges_;
}
template <typename Weight>
const std::vector<typename DirectedWeightedGraph<Weight>::IncidenceList>&
DirectedWeightedGraph<Weight>::GetIncidenceLists() const {
return incidence_lists_;
}
} // namespace graph