Adjacency List Displays a graph using a vector and a pair

I want to implement a presentation of a list of contiguous graphs from a book on competitive programming. 1. The implementation uses a vector of V vertices, and for each vertex v another. a vector that contains pairs (the neighboring vertex and its edge weight) that have a v relationship. I am having problems with inputting this graph and displaying the output.

In the book they made such statements:

#include <iostream> #include <vector> using namespace std; typedef pair<int, int> ii; typedef vector<ii> vii; vector <vii> AdjList; 

How can I take the input of the next graph as an adjacency list and display it as an adjacency list? Suppose each cost of an edge is 10.

Various representation of graphs

+4
graph
source share
1 answer

If we want to read the input of the graph in the form of n vertices and m edges, using the implementation of the adjacency of the graph.

 #include<iostream> #include<vector> using namespace std; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; int main() { int n,m ; cin>>n>>m; vector<vii> adjList(n+1); //For vertex 1...n //Reading edges for the input for graph for(int i=0;i<m;i++) { int u,v; cin>>u>>v; /*Here u->v is the edge and pair second term can be used to store weight in case of weighted graph. */ adjList[u].push_back(make_pair(v,10)); } //To print the edges stored in the adjacency list for(int i=1;i<=n;i++) { for(int j=0;j<(int)adjList[i].size();j++) { cout<<"Edge is "<<i<<" -> "<<adjList[i][j].first<<endl; cout<<"Weight is "<<adjList[i][j].second<<endl; } } return 0; } 
+8
source share

All Articles