Pagini recente » Cod sursa (job #2736617) | Cod sursa (job #2193968) | Cod sursa (job #1706600) | Cod sursa (job #1609197) | Cod sursa (job #2613985)
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <climits>
// #define INF -1
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
struct nodeCost
{
int node, cost;
};
struct classcomp
{
bool operator()(nodeCost a, nodeCost b) const
{
return a.cost < b.cost;
}
};
vector<int> calculateCosts(vector<vector<int>> &graph)
{
set<nodeCost, classcomp> costs;
vector<int> finalCosts(graph.size(), INT_MAX);
costs.insert({0, 0});
for (int i = 1; i < graph.size(); i++)
{
costs.insert({i, INT_MAX});
}
while (costs.size() > 0)
{
auto first = *(costs.begin());
if (first.cost == INT_MAX)
{
break;
}
finalCosts[first.node] = first.cost;
for (int i = 0; i < graph.size(); i++)
{
int drum = graph[first.node][i], lungNou = first.cost + graph[first.node][i];
if (drum != INT_MAX && finalCosts[i] > lungNou)
{
costs.erase({i, finalCosts[i]});
costs.insert({i, lungNou});
finalCosts[i] = lungNou;
}
}
costs.erase(first);
}
return finalCosts;
}
int main()
{
int n, m, a, b, v;
in >> n >> m;
vector<vector<int>> graph(n);
for (int i = 0; i < n; i++)
{
vector<int> tmp(n, INT_MAX);
graph[i] = tmp;
}
for (int i = 0; i < m; i++)
{
in >> a >> b >> v;
graph[a - 1][b - 1] = v;
graph[b - 1][a - 1] = v;
}
auto aa = calculateCosts(graph);
for (int i = 1; i < aa.size(); i++)
{
out << aa[i] << ' ';
}
return 0;
}