I have implemented the Dijkstra's algorithm in C++ with the help of vectors. The problem description is available here. This passes all the test cases except one. The test case input causing the failure is available here
class CompareDistance{
public:
bool operator()(pair<int, int> node1, pair<int, int>node2){
return node1.second > node2.second;
};
};
void dijkstra(vector <list < pair<int, int> > > edgeList, int start, int nodes)
{
priority_queue< pair<int, int>, vector< pair<int, int> >, CompareDistance > q;
vector<int> distance(nodes + 1, -1);
pair<int, int> currentNode;
q.push(make_pair(start, 0));
distance[start] = 0;
while (!q.empty()){
currentNode = q.top();
q.pop();
list< pair <int,int> >::iterator itr = edgeList[currentNode.first].begin();
while(itr != edgeList[currentNode.first].end()){
if(distance[itr->first] == -1 || ( ( distance[currentNode.first] + itr->second ) < distance[itr->first]))
{
distance[itr->first] = distance[currentNode.first] + itr->second;
q.push(make_pair(itr->first, distance[itr->first]));
}
itr++;
}
}
for (int index = 1; index <= nodes; index++){
if(index != start){
cout << distance[index] << " ";
}
}
cout<<endl;
}
int main()
{
int query;
//cout << "Number of queries : ";
cin >> query;
vector < vector < list < pair<int, int> > > > edgeList(query, vector < list < pair <int, int> > >(0));
vector <int> nodes(query), edges(query), start(query);
int index, v1, v2, v3, j;
for (index = 0; index < query; index++){
//cout << "Number of Nodes Edges : ";
cin >> nodes[index] >> edges[index];
edgeList[index].resize(nodes[index] + 1);
for(j = 1; j < edges[index] +1; j++ ){
cin >> v1 >> v2 >> v3;
cout << "Pushing : " << j << endl;
edgeList[index][v1].push_back( make_pair( v2, v3));
edgeList[index][v2].push_back( make_pair( v1, v3));
}
cin >> start[index];
}
for(index = 0; index < query; index++){
dijkstra(edgeList[index], start[index], nodes[index]);
}
}
The above program hangs after printing the below output.
Pushing : 21702
Pushing : 21703
Graph of the last test case has 3121251 edges and my guess is that, vector fails to push all the elements.
Any suggestions on how to fix this are welcome.