Created
December 1, 2016 11:22
-
-
Save lishunan246/b2e8e96b1018d640b08fc7adde600c41 to your computer and use it in GitHub Desktop.
Dijkstra's algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <string> | |
#include <sstream> | |
#include <vector> | |
#include <map> | |
#include <set> | |
#include <algorithm> | |
void split(const std::string &s, char delim, std::vector<std::string> &elems) { | |
std::stringstream ss; | |
ss.str(s); | |
std::string item; | |
while (std::getline(ss, item, delim)) { | |
elems.push_back(item); | |
} | |
} | |
std::vector<std::string> split(const std::string &s, char delim) { | |
std::vector<std::string> elems; | |
split(s, delim, elems); | |
return elems; | |
} | |
struct edge | |
{ | |
unsigned v; | |
unsigned length; | |
}; | |
int main() | |
{ | |
std::ifstream input_file("dijkstra.txt"); | |
std::string line; | |
std::multimap<unsigned, edge> map; | |
while (std::getline(input_file,line)) | |
{ | |
auto words = split(line, '\t'); | |
unsigned s = std::atoi(words[0].c_str()); | |
words.erase(words.begin()); | |
for(auto&& e:words) | |
{ | |
auto p = split(e, ','); | |
unsigned v = std::atoi(p[0].c_str()); | |
unsigned l = std::atoi(p[1].c_str()); | |
edge edge; | |
edge.v = v; | |
edge.length = l; | |
map.insert({ s,edge }); | |
} | |
} | |
unsigned distance[201]; | |
bool visited[201]; | |
std::set<unsigned> q; | |
for(int i=1;i<=200;i++) | |
{ | |
distance[i] = UINT_MAX; | |
q.insert(i); | |
} | |
distance[1] = 0; | |
while (!q.empty()) | |
{ | |
auto min=std::min_element(q.cbegin(),q.cend(),[&distance](unsigned a, unsigned b) | |
{ | |
return distance[a] < distance[b]; | |
}); | |
auto u = *min;; | |
q.erase(min); | |
auto it = map.equal_range(u); | |
for(auto i=it.first;i!=it.second;++i) | |
{ | |
auto p = i->second; | |
auto v = p.v; | |
auto alt = distance[u] + p.length; | |
if(distance[v]>alt) | |
{ | |
distance[v] = alt; | |
} | |
} | |
} | |
std::vector<unsigned> o = { 7,37,59,82,99,115,133,165,188,197 }; | |
for(auto&& x:o) | |
{ | |
std::cout << distance[x] << ','; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment