Pagini recente » Cod sursa (job #1672486) | Cod sursa (job #2866519) | Cod sursa (job #2904918) | Cod sursa (job #242936) | Cod sursa (job #2789136)
#include <fstream>
#include <vector>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
#define inf 5000000001L;
class Graph
{
struct Edge
{
int from;
int to;
int cost;
};
private:
int cntNodes;
vector<vector<Edge>> fromToList;
public:
Graph(int n)
{
cntNodes = n;
for (int i = 0; i < n; ++i)
{
fromToList.push_back(vector<Edge>());
}
}
void addEdge(int from, int to, int cost)
{
fromToList[from].push_back({from, to, cost});
}
vector<long long> dijkstra(int source)
{
vector<long long> d(cntNodes, -1);
d[source] = 0;
auto cmp = [&](const int &a, const int &b) -> bool
{
return d[a] < d[b];
};
priority_queue<int, vector<int>, decltype(cmp)> pq(cmp);
pq.push(source);
while (!pq.empty())
{
int top = pq.top();
pq.pop();
for (Edge e : fromToList[top])
{
if (d[e.to] == -1 || d[e.to] > d[top] + e.cost)
{
d[e.to] = d[top] + e.cost;
pq.push(e.to);
}
}
}
return d;
}
};
int main()
{
int n, m, a, b, c;
fin >> n >> m;
Graph g(n);
while (m-- > 0)
{
fin >> a >> b >> c;
g.addEdge(a - 1, b - 1, c);
}
vector<long long> dist = g.dijkstra(0);
for (int i = 1; i < dist.size(); ++i)
{
fout << (dist[i] == -1 ? 0 : dist[i]) << " ";
}
return 0;
}