VOOZH about

URL: https://www.geeksforgeeks.org/dsa/graph-implementation-using-stl-for-competitive-programming-set-2-weighted-graph/

⇱ Graph implementation using STL for competitive programming | Set 2 (Weighted graph) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Graph implementation using STL for competitive programming | Set 2 (Weighted graph)

Last Updated : 23 Jul, 2025

In Set 1, unweighted graph is discussed. In this post, weighted graph representation using STL is discussed. The implementation is for adjacency list representation of weighted graph. 

👁 Image
Undirected Weighted Graph

We use two STL containers to represent graph: 

  • vector : A sequence container. Here we use it to store adjacency lists of all vertices. We use vertex number as index in this vector.
  • pair : A simple container to store pair of elements. Here we use it to store adjacent vertex number and weight of edge connecting to the adjacent.

The idea is to use a vector of pair vectors. Below code implements the same.


Output
Node 0 makes an edge with 
 Node 1 with edge weight =10
 Node 4 with edge weight =20

Node 1 makes an edge with 
 Node 0 with edge weight =10
 Node 2 with edge weight =30
 Node 3 with edge weight =40
 Node 4 with edge weight =50

Node 2 makes an edge with 
 Node 1 with edge weight =30
 Node 3 with edge weight =60

Node 3 makes an edge with 
 Node 1 with edge weight =40
 Node 2 with edge weight =60
 Node 4 with edge weight =70

Node 4 makes an edge with 
 Node 0 with edge weight =20
 Node 1 with edge weight =50
 Node 3 with edge weight =70

Complexity analysis : 

Time complexity:  O(1), as it takes a constant amount of time to add a new HashMap object to an ArrayList. The time complexity of printing the graph is O(V * E), as it takes O(E) time to print the edges for each vertex, and there are V vertices in the graph.

Auxiliary Space: O(V + E), where V is the number of vertices in the graph and E is the number of edges. This is because the adjacency list uses an ArrayList of ArrayLists to store the graph, and each ArrayList and HashMap object consumes a constant amount of space.

and improved by Kunal Verma
 

Comment
Article Tags:
Article Tags: