vector - What is a better way to optimise space while using graphs (specifically in C++)? -


i represent graphs as:

vector <int> adj[nodes+1]; 

and graph filled follows

  for(int i=0;i<edges;i++){    int a,b; // node 1 & b node 2    cin>>a;    cin>>b;    adj[a].push_back(b);    adj[b].push_back(a); } 

nodes , edges have limits follows:

nodes < 10000 edges < 40000 

hence maximum size of vector of arrays 80,000 (since a->b means b->a) * 4 bytes i.e 312.5 kb?

i applying dijkstra on it, hence have 2 more arrays as:

int distance[nodes+1] bool visited[nodes+1] 

which should take 312.5 & 78.125 kb respectfully , hence total of 703.125 kb of usage. however, program using more 15 mbs of memory.

which brings me question. there multiple test cases , code run multiple times in loop, memory accumulating on each loop? shouldn't variables destroyed each time out of scope?

here's int main() code:

int main() {   int testcases;   cin>>testcases;    int solutions[50];   int size = 0;    (int i=0;i<testcases;i++){     cin>>nodes;    cin>>edges;    cin>>startnode;    cin>>endnode;     vector <int> adj[nodes+1];     for(int i=0;i<edges;i++){      int a,b;      cin>>a;      cin>>b;      adj[a].push_back(b);      adj[b].push_back(a);    }     int ans = cake(adj);    solutions[size] = ans;    size++;   }    (int i=0;i<=size;i++){       cout << solutions[i] << endl;    }   } 

cake (dijkstra)

int cake(vector<int> adj[]){){    bool visited[nodes+1];   int dist[nodes+1];    (int i=0;i<nodes+1;i++){     visited[i]=false;     dist[i]=intmax;   }    dist[startnode] = 0;     (int i=0;i<nodes;i++){    int currentnode = mindist(dist,visited);   visited[currentnode]=true;    bool founddestination = false;    for(int neighbouri = 0; neighbouri<adj[currentnode].size();neighbouri++){        int comparedist = 1 + dist[currentnode];       if (!visited[adj[currentnode][neighbouri]] && comparedist < dist[adj[currentnode][neighbouri]]){         dist[adj[currentnode][neighbouri]]  = comparedist;          if (adj[currentnode][neighbouri] == endnode){           founddestination = true;         }        }   }    if (founddestination){     return dist[endnode];   }   }  return -1;   } 

minimum distance

int mindist(int dist[],bool visited[]){  int min = intmax, min_index;  (int j=1;j<nodes;j++){  if (!visited[j] && dist[j]<min){   min = dist[j];   min_index = j; } } return min_index; } 


Comments