Answers to: Adjacency lists & Adjacency matriceshttps://inoi15.discuss.codechef.com/questions/60720/adjacency-lists-adjacency-matrices<p>I recently implemented DFS by making an adjacency list using a vector of vectors and was pretty pleased about that. But yesterday, I read here <a> </a><a href="http://web.stanford.edu/class/cs97si/">http://web.stanford.edu/class/cs97si/</a> on the basic Graph algorithms slide that an array of vectors is slower than plain arrays.</p>
<p>For me, vectors of vectors was pretty easy to code but just arrays was hard as I had trouble just adding an edge and manipulating the 2 arrays. What do the rest of you recommend me to use taking into account time and memory efficiency? If you recommend arrays, could you also give me a good resource which explains how to easily implement it?</p>
<p>Also, I read that we should use an adjacency matrix only when the graph is dense (No. of vertices is almost equal to no. of edges). But what if the constraints (around 10^5 edges) are such that it is too large even for the global scope? What do I use to represent the edge relations in such a case?</p>enSun, 04 Jan 2015 16:42:46 +0530Answer by supertyhttps://inoi15.discuss.codechef.com/questions/60720/adjacency-lists-adjacency-matrices/60721<p>I have never come across any slowness issues using an array of vectors.</p>
<p>But do use an array of vectors, not a vector of vectors. Usually you know the number of vertexes, so</p>
<pre><code>vector<int> e[MAXIMUM_NO_OF_VERTICES]
</code></pre>
<p>should be sufficient, where e[v][i] is the ith vertex that v is connected to. It's also easier IMO than a vector of vectors.</p>
<p>Also, dense means that the number of edges is nearly the number of pairs of vertices, not number of vertexes.
A vertex with number of edges around the number of vertices is a very sparse graph.</p>
<p>An adjacency matrix is feasible only if N^2 is pretty small. For number of vertexes around 10^5 the size of an adjacency matrix is 4*10^10 (around 40 GB) which is certainly not going to fit within any memory limit. In such cases you must use an adjacency list, which will fit in O(number of edges) memory space. Number of edges can be around 10^5, it still takes up only around 800 KB. (4 bytes per int * 2 vertices per edge * 100000 edges)</p>supertySun, 04 Jan 2015 16:42:46 +0530https://inoi15.discuss.codechef.com/questions/60720/adjacency-lists-adjacency-matrices/60721