n8118's blog

By n8118, history, 9 years ago, In English

How to implement weighted Graph in c++ for higher values of n = 10^5 (n vertices graph)?? If n = 10^3 i generally implement using adjacency matrix or by using vector stl.

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
Rev. 2   Vote: I like it +14 Vote: I do not like it

You can implement it using adjacency lists. Something as simple as this works...

// Declare adjacency list

vector<pair<int,int>> E[100005];

// Add an edge u,v with weight w

E[u].push_back({v,w});

// Process all edges u,v with cost w from node u

for(pair<int,int> p : E[u])
{
    int v = p.first, w = p.second;

    // Do something...
}
  • »
    »
    9 years ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    Thanks a lot!!

  • »
    »
    17 months ago, # ^ |
    Rev. 3   Vote: I like it -36 Vote: I do not like it

    It only works for a directional graph.

    • »
      »
      »
      17 months ago, # ^ |
      Rev. 2   Vote: I like it +6 Vote: I do not like it

      i think you need to understand how the code above works instead of just taking it its basically creating an array of vectors every slot of the array represent a node so lets say i want to add a link from node u to node v then i will just push v in the uth slot thats why i need to do something like this: e[u].push_back({v, whatever_weight}) now, we want to make undirected graph just instead just adding u to slot v we also add v to slot u so conclusion just add e[v].push_back({u, w}) as well to make an undirected graph

»
17 months ago, # |
Rev. 2   Vote: I like it -9 Vote: I do not like it

My bad