Pagini recente » Cod sursa (job #3167535) | Cod sursa (job #3178776) | Cod sursa (job #683704) | Cod sursa (job #2157757) | Cod sursa (job #2789141)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
class Graph
{
struct Edge
{
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({to, cost});
}
void dijkstra(long long d[], int source)
{
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);
}
}
}
}
};
long long dist[50013];
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);
}
fill(dist, dist + n, -1);
g.dijkstra(dist, 0);
for (int i = 1; i < n; ++i)
{
fout << (dist[i] == -1 ? 0 : dist[i]) << " ";
}
return 0;
}