Pagini recente » Cod sursa (job #1202046) | Cod sursa (job #1572244) | Cod sursa (job #2682760)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int nMax = 50001;
const int inf = (1 << 30);
int n, m;
vector <pair<int, int>> l[nMax];
priority_queue <pair <int, int>> q;
bool viz[nMax];
int dist[nMax];
void Citire()
{
fin >> n >> m;
int x, y, d;
for (int i = 0; i <= m; i++)
{
fin >> x >> y >> d;
l[x].push_back({ y, d });
}
fin.close();
}
void Dijkstra(int nod)
{
for (int i = 1; i <= n; i++)
dist[i] = inf;
dist[nod] = 0;
q.push({ 0, nod });
while (!q.empty())
{
int nod = q.top().second;
int cost = -q.top().first;
q.pop();
if (!viz[nod])
{
viz[nod] = 1;
for (auto it : l[nod])
{
int newNod = it.first;
int newCost = it.second;
if (dist[newNod] > dist[nod] + newCost)
{
dist[newNod] =dist[nod] + newCost;
q.push({ -dist[newNod],newNod });
}
}
}
}
}
int main()
{
Citire();
Dijkstra(1);
for (int i = 2; i <= n; i++)
{
if (dist[i] == inf)fout << "0 ";
else fout << dist[i] << " ";
}
fout << "\n";
return 0;
}