https://sites.google.com/site/indy256/algo_cpp/dijkstra_heap
#include <iostream>
#include <fstream>
#include <math.h>
#include <vector>
#include <sstream>
#include <map>
using namespace std;
int heap[1000];
int prior[1000];
int heapSize = 0;
//int pos2Id[1000];
int id2Pos[1000];
bool boolX[1000];
void InsertHeap(int id)
{
heap[heapSize++] = id;
id2Pos[id] = heapSize-1;
int pos = heapSize-1;
while (pos > 0)
{
int parent = pos-1 >> 1;
if(prior[id] > prior[heap[parent]])
{
break;
}
int temp = heap[parent];
heap[parent] = id;
heap[pos] = temp;
id2Pos[id] = parent;
id2Pos[temp] = pos;
pos = parent;
}
}
void DeleteHeap(int id)
{
int pos = id2Pos[id];
if (pos < 0)
{
return;
}
heap[pos] = heap[--heapSize];
id2Pos[heap[pos]] = pos;
while (pos < (heapSize>>1))
{
int child = 2*pos+1;
if (child+1< heapSize && prior[heap[child+1]] < prior[heap[child]])
{
child++;
}
if (prior[heap[pos]] <= prior[heap[child]])
{
break;
}
int temp = heap[pos];
heap[pos] = heap[child];
heap[child] = temp;
id2Pos[temp] = child;
id2Pos[heap[pos]] = pos;
pos = child;
}
}
int PopMin()
{
int id = heap[0];
heap[0] = heap[--heapSize];
int pos = 0;
id2Pos[heap[pos]] = pos;
while (pos < (heapSize>>1))
{
int child = 2*pos+1;
if (child+1< heapSize && prior[heap[child+1]] < prior[heap[child]])
{
child++;
}
if (prior[heap[pos]] <= prior[heap[child]])
{
break;
}
int temp = heap[pos];
heap[pos] = heap[child];
heap[child] = temp;
id2Pos[temp] = child;
id2Pos[heap[pos]] = pos;
pos = child;
}
return id;
}
void Dijkstra(vector<vector<pair<int, int>>> g, int s)
{
int numV = g.size();
prior[s] = 0;
InsertHeap(s);
while(heapSize >0)
{
int u = PopMin();
boolX[u] = true;
for (int i=0; i<g[u].size(); i++)
{
int v = g[u][i].first;
int w = g[u][i].second;
if (boolX[v-1])
{
continue;
}
DeleteHeap(v-1);
prior[v-1] = min(prior[v-1], prior[u]+w);
InsertHeap(v-1);
}
}
}
int main()
{
ifstream infile;
infile.open("dijkstraData.txt");
// ------------- Read the Graph --------------
vector<vector<pair<int, int>>> graph;
const int numV = 200;
vector<pair<int, int>> temp;
for (int i=0; i< numV; i++)
{
graph.push_back(temp);
}
string line;
char cline[10000];
/*while (infile.getline(cline, 10000))*/
while(getline(infile, line))
{
std::stringstream ss;
ss << line;
int u;
int v;
char t;
int w;
ss >> u;
while(ss >> v)
{
ss >> t;
ss >> w;
graph[u-1].push_back(make_pair(v, w));
}
ss.clear();
line.clear();
}
// --------------
for (int i=0; i<numV; i++)
{
id2Pos[i] = -1;
prior[i] = 1000000;
boolX[i] = false;
}
Dijkstra(graph, 0);
int r[]= {7,37,59,82,99,115,133,165,188,197};
for (int i=0; i<10; i++)
{
cout<< r[i] << " : " << prior[r[i]-1] << endl;
/*cout << prior[i] << endl;*/
}
infile.close();
graph.clear();
return 0;
}