Pagini recente » Cod sursa (job #817320) | Cod sursa (job #1786072) | Borderou de evaluare (job #156735) | Cod sursa (job #1539777) | Cod sursa (job #2968152)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
#define Inf 1000000000
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
using PI = pair<int, int>; /// pereche
int n, m, x, y, D[50001], w;
vector<PI> G[50001];
void dis()
{
for (int i = 1; i <= n; ++i) {
cout << "(Nod " << i << ", Cost " << D[i] << ") ";
}
cout << endl;
}
void dijkstra(int nod)
{
priority_queue < PI , vector<PI> , greater<PI> > Q;
D[nod] = 0;
Q.push({0 , nod});
while(!Q.empty())
{
x = Q.top().first; /// COSTUL MINIM DE LA NODUL SURSA PANA LA NODUL y (NODUL CURENT)
y = Q.top().second; /// NODUL CURENT
Q.pop();
//if(x > D[y]) continue;
int k = G[y].size();
for(int i = 0; i < k; ++i)
{
int nodnou = G[y][i].first; /// NOD VECIN
int costnou = G[y][i].second; /// COST MUCHIE
if(D[nodnou] > D[y] + costnou) /// D[nodnou] = costul nodului vecin , D[y] = costul nodului curent , costnou = costul muchiei ce leaga cele doua noduri
{
D[nodnou] = D[y] + costnou; /// ACTUALIZAM COSTUL NODULUI VECIN
Q.push({D[nodnou] , nodnou}); /// INTRODUCEM IN COADA COSTUL PANA LA NODUL VECIN SI PE ACESTA
}
}
}
}
int main()
{
fin >> n >> m;
for (int i = 0; i < m; ++i) {
fin >> x >> y >> w;
G[x].push_back({y , w});
}
for(int i = 1 ; i <= n ; i++)
D[i] = Inf;
dijkstra(1);
for(int i = 2; i <= n ; i++)
if (D[i] == Inf) {
fout << 0 << ' ';
}
else {
fout << D[i] << " ";
}
}