我在矢量的帮助下用C ++实现了Dijkstra算法。问题描述可用here。这通过了除一个以外的所有测试用例。导致失败的测试用例输入可用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]);
}
}
打印下面的输出后,上述程序挂起。
Pushing : 21702
Pushing : 21703
最后一个测试用例的图表有3121251个边缘,我的猜测是,向量无法推送所有元素。
欢迎任何有关如何解决此问题的建议。