C++ verzia (dufam ze tam nemam chybu):
#include <vector>
#include <limits>
#include <chrono>
#include <iostream>
#include <cstdlib>
const int INT_MAX = std::numeric_limits<int>::max();
int compute (int count, int start, int stop, const std::vector<int> &weight)
{
std::vector<bool> invalid(count, false);
std::vector<int> distance(count, INT_MAX);
int u = start;
distance[u] = 0;
while(u != stop) {
invalid[u] = true;
int minDistance = distance[u];
int min = INT_MAX;
for (int v = 0; v < count; ++v) {
if (invalid[v]) {
continue;
}
int distanceThroughU = minDistance + weight[u * count + v];
if (distanceThroughU < distance[v]) {
distance[v] = distanceThroughU;
}
if (distance[v] < min) {
u = v;
min = distance[v];
}
}
}
return distance[u];
}
int main(int argc, char **argv)
{
auto start = std::chrono::high_resolution_clock::now();
const int COUNT = 5000;
std::vector<int> weight(COUNT * COUNT);
srand(time(0));
for (int i = 0; i < COUNT * COUNT; ++i) {
weight[i] = (random() % 100) + 1;
}
int res = compute(COUNT, 0, COUNT - 1, weight);
auto end = std::chrono::high_resolution_clock::now();
int duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << "result: " << res << std::endl;
std::cout << "time : " << duration << std::endl;
return 0;
}
Casy (priemer 50 spusteni, prvy stlpec je vypis casu s programu, druhy s programu time):
Java : 479ms, real 561ms
G++ : 373ms, real 384ms
Clang: 362ms, real 376ms
Java verziu som spustal len prikazom time java Dijkstra, mozno by to poladil nejaky parameter?
C++ verzie su kompilovane prikazmi (medzi -O2 a -O3 nieje podstatny rozdiel):
g++ -std=c++11 -O2 Dijkstra.cpp -o Dijkstra_gcc
clang++ -std=c++11 -O2 Dijkstra.cpp -o Dijkstra_clang