Pagini recente » Cod sursa (job #2893286) | Infoarena Monthly 2014, Runda 9 | Cod sursa (job #587050) | Cod sursa (job #41379) | Cod sursa (job #2437091)
#include<iostream>
#include<iterator>
#include<vector>
#include<list>
#include<queue>
#include<fstream>
#include<algorithm>
// #include "CountSort.h";
// #include "BinarySearch.h";
// #include "Tree.h"
using namespace std;
int Search(const string& str, const string& substr)
{
return -1;
}
struct edge
{
int nextNode{};
int cost{};
};
vector<int> Dijkstra(const vector<list<edge>>& graph, int initialNode)
{
vector<int> cost(graph.size(), numeric_limits<int>::max());
cost[initialNode] = 0;
priority_queue<int> heap;
heap.push(initialNode);
while (!heap.empty())
{
auto node = heap.top();
heap.pop();
for (const auto& edge : graph.at(node))
{
if (cost[node] + edge.cost < cost[edge.nextNode])
{
cost[edge.nextNode] = cost[node] + edge.cost;
heap.push(edge.nextNode);
}
}
}
return cost;
}
int main()
{
// string str = "You'll #neversea algorithms like these";
// string substr = "neversea";
//
// int pos = Search(str, substr);
// if (pos != -1)
// {
// cout << "Subsirul a fost gasit pe pozitia : " << pos << endl;
// }
// else
// {
// cout << "Subsirul nu a fost gasit" << endl;
// }
// read input data
ifstream in("dijkstra.in");
int nodesCount{};
int edgesCount{};
in >> nodesCount;
in >> edgesCount;
vector<list<edge>> graph(nodesCount + 1, list<edge>{});
for (int i = 0; i < nodesCount; ++i)
{
int from{}, to{}, cost{};
in >> from >> to >> cost;
graph[from].push_back({ to, cost });
graph[to].push_back({from, cost});
}
// run dijkstra
auto costs = Dijkstra(graph, 1);
// write output data
ofstream out("dijkstra.out");
for (int i = 2; i < costs.size(); ++i)
out << costs[i] << " ";
}