The Wayback Machine - https://web.archive.org/web/20240817060151/https://www.geeksforgeeks.org/graph-implementation-using-stl-for-competitive-programming-set-2-weighted-graph/
Open In App

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

Last Updated : 05 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

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.

C++




// C++ program to represent undirected and weighted graph
// using STL. The program basically prints adjacency list
// representation of graph
#include <bits/stdc++.h>
using namespace std;
 
// To add an edge
void addEdge(vector <pair<int, int> > adj[], int u,
                                     int v, int wt)
{
    adj[u].push_back(make_pair(v, wt));
    adj[v].push_back(make_pair(u, wt));
}
 
// Print adjacency list representation of graph
void printGraph(vector<pair<int,int> > adj[], int V)
{
    int v, w;
    for (int u = 0; u < V; u++)
    {
        cout << "Node " << u << " makes an edge with \n";
        for (auto it = adj[u].begin(); it!=adj[u].end(); it++)
        {
            v = it->first;
            w = it->second;
            cout << "\tNode " << v << " with edge weight ="
                 << w << "\n";
        }
        cout << "\n";
    }
}
 
// Driver code
int main()
{
    int V = 5;
    vector<pair<int, int> > adj[V];
    addEdge(adj, 0, 1, 10);
    addEdge(adj, 0, 4, 20);
    addEdge(adj, 1, 2, 30);
    addEdge(adj, 1, 3, 40);
    addEdge(adj, 1, 4, 50);
    addEdge(adj, 2, 3, 60);
    addEdge(adj, 3, 4, 70);
    printGraph(adj, V);
    return 0;
}


Java




import java.util.*;
 
// Creation of Adjacency List
// The adjacency List consist of an ArrayList within an
// ArrayList. The inner ArrayList holds the HashMap of
// (vertices,weight)
public class Weighted_Graph {
    int v;
    ArrayList<ArrayList<HashMap<Integer, Integer> > > adj;
    Weighted_Graph(int v)
    {
        this.v = v;
        this.adj = new ArrayList<>();
 
        for (int i = 0; i < v; i++) {
            this.adj.add(new ArrayList<>());
        }
    }
    // Function to add an Edge
    void addEdge(int u, int v, int weight)
    {
        this.adj.get(u).add(new HashMap<>());
        this.adj.get(u)
            .get(this.adj.get(u).size() - 1)
            .put(v, weight);
 
        this.adj.get(v).add(new HashMap<>());
        this.adj.get(v)
            .get(this.adj.get(v).size() - 1)
            .put(u, weight);
    }
 
    // Function for printing the whole graph
    // Stream API has been used
    // to easily access the HashMap elements
    // This code may not work in versions
    // prior to java 8
 
    void printGraph()
    {
        for (int i = 0; i < this.v; i++) {
            System.out.println("\nNode " + i
                               + " makes an edge with ");
            for (HashMap<Integer, Integer> j :
                 this.adj.get(i)) {
                j.entrySet().forEach(
                    e
                    -> System.out.println(
                        "\tNode " + e.getKey()
                        + " with edge weight "
                        + e.getValue() + " "));
            }
        }
    }
    // Main method
    public static void main(String[] args)
    {
        int v = 5;
        Weighted_Graph obj = new Weighted_Graph(v);
        obj.addEdge(0, 1, 10);
        obj.addEdge(0, 4, 20);
        obj.addEdge(1, 2, 30);
        obj.addEdge(1, 3, 40);
        obj.addEdge(1, 4, 50);
        obj.addEdge(2, 3, 60);
        obj.addEdge(3, 4, 70);
        obj.printGraph();
    }
}
// This code is submitted by Abhishek_Manna_HETC


Python3




# Python3 program to represent undirected
# and weighted graph. The program basically
# prints adjacency list representation of graph
 
# To add an edge
def addEdge(adj, u, v, wt):
     
    adj[u].append([v, wt])
    adj[v].append([u, wt])
    return adj
 
# Print adjacency list representation of graph
def printGraph(adj, V):
     
    v, w = 0, 0
    for u in range(V):
        print("Node", u, "makes an edge with")
 
        for it in adj[u]:
            v = it[0]
            w = it[1]
            print("\tNode", v, "with edge weight =", w)
             
        print()
 
# Driver code
if __name__ == '__main__':
     
    V = 5
    adj = [[] for i in range(V)]
 
    adj = addEdge(adj, 0, 1, 10)
    adj = addEdge(adj, 0, 4, 20)
    adj = addEdge(adj, 1, 2, 30)
    adj = addEdge(adj, 1, 3, 40)
    adj = addEdge(adj, 1, 4, 50)
    adj = addEdge(adj, 2, 3, 60)
    adj = addEdge(adj, 3, 4, 70)
 
    printGraph(adj, V)
 
# This code is contributed by mohit kumar 29


C#




using System;
using System.Collections.Generic;
 
// Code Addition(C#)
// C# contribution to existing topic
// "Graph implementation using STL for
// competitive programming | Set 2 (Weighted graph)"
class WeightedGraph
   {
       private int V;
 
       private LinkedList<Tuple<int, int>>[] adj;
 
       public WeightedGraph(int v)
       {
           this.V = v;
 
           adj = new LinkedList<Tuple<int, int>>[v];
 
           for (int i=0;i < v; i++)
           {
               adj[i] = new LinkedList<Tuple<int, int>>();
           }
       }
 
 
       public void addEdge(int u, int v, int wt)
       {
           adj[u].AddLast(Tuple.Create(v, wt));
           adj[v].AddLast(Tuple.Create(u, wt));
 
       }
 
       public void printGraph()
       {
           for (int i=0; i< this.V;i++)
           {
               Console.WriteLine("\nNode " + i + " makes an edge with ");
               foreach (var j in adj[i])
               {
                   Console.WriteLine("\tNode " + j.Item1 + " with edge weight " + j.Item2 + " ");
               }
             
           }
       }
 
       static void Main(string[] args)
       {
 
           int V = 5;
           WeightedGraph stl = new WeightedGraph(V);
 
 
           stl.addEdge(0, 1, 10);
           stl.addEdge(0, 4, 20);
           stl.addEdge(1, 2, 30);
           stl.addEdge(1, 3, 40);
           stl.addEdge(1, 4, 50);
           stl.addEdge(2, 3, 60);
           stl.addEdge(3, 4, 70);
           stl.printGraph();
 
           Console.ReadKey();
 
       }
   }
 
// This code is contributed by realchid.


Javascript




<script>
// Javascript program to represent undirected and weighted graph
// using STL. The program basically prints adjacency list
// representation of graph
 
    // To add an edge
    function addEdge(adj,u,v,wt)
    {
        adj[u].push([v,wt]);
        adj[v].push([u,wt]);
        return adj;
       
    }
     
    //Print adjacency list representation of graph
    function printGraph(adj, V)
    {
        let v=0,w=0;
        for(let u=0;u<V;u++)
        {
            document.write("Node "+u+ " makes an edge with<br>");
            for(let it=0;it<adj[u].length;it++)
            {
                v=adj[u][it][0];
                w=adj[u][it][1];
                document.write("        Node "+ v+ " with edge weight ="+ w+"<br>")
            }
        }
    }
     
     
    // Driver code
    let V = 5;
     
    // The below line may not work on all
    // compilers.  If it does not work on
    // your compiler, please replace it with
    // following
    // vector<int> *adj = new vector<int>[V];
    let adj=new Array(V);
    for(let i=0;i<V;i++)
    {
        adj[i]=[];
    }
     
    // Vertex numbers should be from 0 to 4.
    adj = addEdge(adj, 0, 1, 10)
    adj = addEdge(adj, 0, 4, 20)
    adj = addEdge(adj, 1, 2, 30)
    adj = addEdge(adj, 1, 3, 40)
    adj = addEdge(adj, 1, 4, 50)
    adj = addEdge(adj, 2, 3, 60)
    adj = addEdge(adj, 3, 4, 70)
    printGraph(adj, V);
     
     
     
    // This code is contributed by unknown2108
</script>


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

 



Previous Article
Next Article

Similar Reads

Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
We have introduced Graph basics in Graph and its representations. In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. Following is an example undirected and unweighted graph with 5 vertices. Below is an adj
7 min read
Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Prefix Sum Array - Implementation and Applications in Competitive Programming
Given an array arr[] of size N, find the prefix sum of the array. A prefix sum array is another array prefixSum[] of the same size, such that the value of prefixSum[i] is arr[0] + arr[1] + arr[2] . . . arr[i]. Examples: Input: arr[] = {10, 20, 10, 5, 15}Output: prefixSum[] = {10, 30, 40, 45, 60}Explanation: While traversing the array, update the el
15+ min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Top Programming Languages For Competitive Programming
Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are almost more than 700 programming languages which are the most popular ones and this number will increase day by day. But, you don't need to learn all of them. Having a good command of anyone is enough for you to grow your
13 min read
Shortest path with exactly k edges in a directed and weighted graph | Set 2
Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1. Examples: Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The shortest path with two edges will be 1-&gt;2-&gt;3
8 min read
Graph Coloring for Competitive Programming
Graph coloring in programming refers to the assignment of colors to the vertices of a graph in a way that no two adjacent vertices share the same color. In this article, we will cover the concepts of Graph coloring, why is it important to learn for Competitive Programming and other related concepts like: Bipartite Graph, Chromatic Number, etc. Tabl
9 min read
BFS using STL for competitive coding
A STL based simple implementation of BFS using queue and vector in STL. The adjacency list is represented using vectors of vector.  In BFS, we start with a node. Create a queue and enqueue source into it. Mark source as visited.While queue is not empty, do followingDequeue a vertex from queue. Let this  be f.Print fEnqueue all not yet visited adjac
5 min read
Shortest path with exactly k edges in a directed and weighted graph
Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with exactly k edges on the path. The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j. For example, consider the follow
15+ min read
Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
Given a directed graph, which may contain cycles, where every edge has weight, the task is to find the minimum cost of any simple path from a given source vertex ‘s’ to a given destination vertex ‘t’. Simple Path is the path from one vertex to another such that no vertex is visited more than once. If there is no simple path possible then return INF
10 min read
Number of spanning trees of a weighted complete Graph
Prerequisites: Graph Theory Basics, Spanning tree. Complete Weighted Graph: A graph in which an edge connects each pair of graph vertices and each edge has a weight associated with it is known as a complete weighted graph. The number of spanning trees for a complete weighted graph with n vertices is n(n-2). Proof: Spanning tree is the subgraph of g
4 min read
Number of shortest paths in an Undirected Weighted Graph
Given a weighted undirected graph G and an integer S, the task is to print the distances of the shortest paths and the count of the number of the shortest paths for each node from a given vertex, S. Examples: Input: S =1, G = Output: Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 Numbers of the shortest Paths are: 1 1 1 2 3 1 1 1 2 Explanation: T
15 min read
In a weighted graph, Is zero allowed as an edge's weight?
In this article, we will discuss the overview of the Graph and will focus on a scenario wherein a weighted graph, Is zero allowed as an edge's weight. Let's discuss it one by one as follows. Overview :A graph is defined as a G(V, E) where V is a set of vertices and E is the set of edges. The interconnected point from one object to another object is
3 min read
Minimum cost of path between given nodes containing at most K nodes in a directed and weighted graph
Given a directed weighted graph represented by a 2-D array graph[][] of size n and 3 integers src, dst, and k representing the source point, destination point, and the available number of stops. The task is to minimize the cost of the path between two nodes containing at most K nodes in a directed and weighted graph. If there is no such route, retu
10 min read
What is Weighted Graph with Applications, Advantages and Disadvantages
What is Weighted Graph? A weighted graph is defined as a special type of graph in which the edges are assigned some weights which represent cost, distance, and many other relative measuring units. Applications of Weighted Graph:2D matrix games: In 2d matrix, games can be used to find the optimal path for maximum sum along starting to ending points
5 min read
Shortest Path in a weighted Graph where weight of an edge is 1 or 2
Given a directed graph where every edge has weight as either 1 or 2, find the shortest path from a given source vertex ‘s’ to a given destination vertex ‘t’. Expected time complexity is O(V+E). A Simple Solution is to use Dijkstra’s shortest path algorithm, we can get a shortest path in O(E + VLogV) time. How to do it in O(V+E) time? The idea is to
15 min read
Monotonic shortest path from source to destination in Directed Weighted Graph
Given a weighted directed graph with N vertices and M edges, a source src and a destination target, the task is to find the shortest monotonic path (monotonically increasing or decreasing) from the source to the destination. Output -1 if no monotonic path is possible. Note: All weights are non-negative Examples: Input: N = 6, M = 9, src = 1, target
14 min read
Number of distinct Shortest Paths from Node 1 to N in a Weighted and Directed Graph
Given a directed and weighted graph of N nodes and M edges, the task is to count the number of shortest length paths between node 1 to N. Examples: Input: N = 4, M = 5, edges = {{1, 4, 5}, {1, 2, 4}, {2, 4, 5}, {1, 3, 2}, {3, 4, 3}}Output: 2Explanation: The number of shortest path from node 1 to node 4 is 2, having cost 5. Input: N = 3, M = 2, edge
10 min read
Find palindromic path of given length K in a complete Binary Weighted Graph
Given a complete directed graph having N vertices, whose edges weighs '1' or '0', the task is to find a path of length exactly K which is a palindrome. Print "YES" if possible and then the path, otherwise print "NO".  Example:  Input: N = 3, K = 4edges[] =  {{{1, 2}, '1'}, {{1, 3}, '1'}, {{2, 1}, '1'}, {{2, 3}, '1'}, {{3, 1}, '0'}, {{3, 2}, '0'}}Ou
15+ min read
Minimum Distance to a Leaf Node in a Weighted Undirected Graph
Given an undirected tree having N nodes numbered from 0 to N - 1. Additionally, a 2D integer array, edges[][] of length N - 1, is provided, where edges[i]=[u, v, w] indicates an undirected edge between nodes u and v with a weight w. The task is to return an answer array of length N, where answer[i] represents the minimum time required for i'th node
12 min read
Josephus Circle implementation using STL list
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the execut
6 min read
Interactive Problems in Competitive Programming | Set 2
Introduction to interactive problems in competitive programming is already discussed in the previous article. In this article, another problem based on the same concept is discussed. Assume that the judge has a hidden (it means the user can't access it) sorted array. The user (i.e. you) need to tell whether a given element VAL lies in that sorted a
3 min read
Input/Output from external file in C/C++, Java and Python for Competitive Programming | Set 2
Prerequisites : Input/Output from external file in C/C++, Java and Python for Competitive Programming In above post,  we saw a way to have standard input/output from external file using file handling. In this post, we will see a very easy way to do this. Here we will compile and run our code from terminal or cmd using  input and output streams. Win
3 min read
Weighted Job Scheduling | Set 2 (Using LIS)
Given N jobs where every job is represented by following three elements of it.1. Start Time 2. Finish Time 3. Profit or Value AssociatedFind the maximum profit subset of jobs such that no two jobs in the subset overlap. Examples: Input: Number of Jobs n = 4 Job Details {Start Time, Finish Time, Profit} Job 1: {1, 2, 50} Job 2: {3, 5, 20} Job 3: {6,
10 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Setting up Sublime Text For Competitive Programming (C++) Using Fast Olympic Coding Plugin
Competitive Programming is a mind sport where time matters the most. For that, a fast and easy-to-use tool is required for writing code. Sublime text along with the CppFastOlympicCoding plugin provides the same. Sublime text is popular for its fast performance and aesthetic UI. The CppFastOlympicCoding plugin offers features such as: TestManager: W
4 min read
Customized Debugging in Sublime Text using C++ for Competitive Programming
Competitive Programming is a mental sport that enables us to code a given problem under provided constraints. The purpose of this article is to guide every individual on how they can debug their code efficiently during a contest.Prerequisite: Setting up Sublime Text for C++ Competitive Programming Environment Time is something that is precious and
15+ min read
Weighted sum of the characters of a string in an array | Set 2
You are given an array of strings str[], the task is to find the score of a given string s from the array. The score of a string is defined as the product of the sum of its characters’ alphabetical values with the position of the string in the array. Examples: Input: str[] = {"sahil", "shashanak", "sanjit", "abhinav", "mohit"}, s = "abhinav" Output
10 min read
Test Case Generation | Set 3 (Unweighted and Weighted Trees)
Generating Random Unweighted Trees Since this is a tree, the test data generation plan is such that no cycle gets formed.The number of edges is one less than the number of verticesFor each RUN we first print the number of vertices - NUM first in a new separate line and the next NUM-1 lines are of the form (a b) where a is the parent of b C/C++ Code
15+ min read
Practice Tags :
three90RightbarBannerImg