我一直在尝试解决SPOJ上的SHPATH问题,这只是Djikstra算法的直接实现。
http://www.spoj.com/problems/TSHPATH/
#include <iostream>
#include <map>
#include <queue>
using namespace std;
class Graph{
public:
vector< pair<int,int> > adjList[10001];
void addEdge(int city_index, int neighbor, int dist){
adjList[city_index].push_back(make_pair(neighbor,dist));
}
};
struct comp{
bool operator()(const pair<int,int>& a, const pair<int,int>& b){
return a.second > b.second;
}
};
int dijkstra(Graph graph, int n, int source, int dest){
priority_queue< pair<int,int>, vector< pair<int,int> >, comp> pqi;
map<int,int> visited;
int curr_dist;
vector< pair<int,int> > curr;
//Start from the source
pqi.push(make_pair(source,0));
while(visited.size() < n && pqi.empty == false){
//Check if it is already visited, If already visited, then ignore
while(visited.find(pqi.top().first) != visited.end()){
pqi.pop();
}
curr = graph.adjList[pqi.top().first];
curr_dist = pqi.top().second;
//Mark it as visited
visited[pqi.top().first] = curr_dist;
pqi.pop();
//Visit all the neighbors
for(int j=0; j<curr.size(); j++){
//If not already visited, then visit it
if(visited.find(curr[j].first) == visited.end()){
pqi.push(make_pair(curr[j].first,curr_dist+curr[j].second));
}
}
}
return visited[dest];
}
int main() {
int t,n,neighbors,a,b,queries;
string city1,city2;
string city_name;
string emptyline;
map<string,int> city_index;
cin>>t;
for(int testcase=0; testcase<t; testcase++){
Graph graph = Graph();
cin>>n;
for(int city=1; city<=n; city++){
cin>>city_name;
city_index[city_name] = city;
cin>>neighbors;
for(int neighbor=0; neighbor<neighbors; neighbor++){
cin>>a>>b;
graph.addEdge(city,a,b);
}
}
cin>>queries;
for(int query=0; query<queries; query++){
cin>>city1>>city2;
cout<<dijkstra(graph,n,city_index[city1],city_index[city2])<<endl;
}
getline(cin,emptyline);
}
return 0;
}
我已经针对来自http://spojtoolkit.com/test/SHPATH
的大量测试用例进行了测试它给出了所有测试用例的正确答案。似乎无法弄清楚,在哪里发生了分段错误,因为没有数组索引超出界限且没有野性指针等。
答案 0 :(得分:0)
在函数djikstra()
中,此行已被修改:
while(visited.size() < n && pqi.empty() == false)
现在,对于所有测试用例,解决方案运行正常。