@@ -45,6 +45,8 @@ class Graph {
4545 if (vertices.count (source) == 0 || vertices.count (target) == 0 ) {
4646 return false ;
4747 }
48+
49+ invalidateCachedEdges ();
4850 outEdges[source].insert (target);
4951 inEdges[target].insert (source);
5052 return true ;
@@ -62,15 +64,18 @@ class Graph {
6264
6365 bool empty () const { return vertices.empty (); }
6466
65- const std::set<V>& getVertices () { return vertices; }
66- std::set<std::pair<V, V>> getEdges () const {
67- std::set<std::pair<V, V>> result;
67+ const std::set<V>& getVertices () const { return vertices; }
68+ const std::set<std::pair<V, V>>& getEdges () const {
69+ if (!edgesDirty) return cachedEdges;
70+
71+ cachedEdges.clear ();
72+ edgesDirty = false ;
6873 for (const auto & [source, targets] : outEdges) {
6974 for (const auto & target : targets) {
70- result .insert ({source, target});
75+ cachedEdges .insert ({source, target});
7176 }
7277 }
73- return result ;
78+ return cachedEdges ;
7479 }
7580
7681 // Returns the edges that point out of the given vertex.
@@ -112,6 +117,7 @@ class Graph {
112117 std::function<void (V&, const V&)> mergeFn = nullptr) {
113118 if (!hasEdge (source, target)) return false ;
114119
120+ invalidateCachedEdges ();
115121 // Merge target into source
116122 if (mergeFn) mergeFn (source, target);
117123
@@ -488,10 +494,13 @@ class Graph {
488494 }
489495
490496 private:
497+ void invalidateCachedEdges () { edgesDirty = true ; }
491498 std::set<V> vertices;
492499 std::map<V, std::set<V>> outEdges;
493500 std::map<V, std::set<V>> inEdges;
494501 std::map<std::pair<V, V>, int > weights;
502+ mutable std::set<std::pair<V, V>> cachedEdges;
503+ mutable bool edgesDirty = true ;
495504};
496505
497506template <typename V>
0 commit comments