Pagini recente » Cod sursa (job #2820348) | Cod sursa (job #1726000) | Cod sursa (job #1025382) | Cod sursa (job #1561338) | Cod sursa (job #3258172)
#include <fstream>
#include <climits>
#include <vector>
#include <queue>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int nmax = 50005;
const int inf = INT_MAX;
struct ceva{
int cost, vec;
};
int n, m, dist[nmax], fr[nmax];
vector< ceva > v[nmax];
priority_queue< pair<int, int> > H;
int find_Min()
{
while(!H.empty() && fr[H.top().second])
H.pop();
if(H.empty())
return -1;
int aux = H.top().second; H.pop();
return aux;
}
void Dijk(int rad)
{
for(int i = 1; i <= n; i ++)
dist[i] = inf;
dist[rad] = 0;
H.push(make_pair(0, rad));
for(int w = 1; w <= n; w ++)
{
int nod = find_Min();
if(nod == -1)
return;
fr[nod] = 1;
for(auto nr : v[nod])
if(dist[nr.vec] > dist[nod] + nr.cost)
{
dist[nr.vec] = dist[nod] + nr.cost;
H.push(make_pair(-dist[nr.vec], nr.vec));
}
}
}
int main()
{
f >> n >> m;
for(int i = 1; i <= m; i ++){
int x, y, c; f >> x >> y >> c;
v[x].push_back({c, y});
}
Dijk(1);
for(int i = 2; i <= n; i ++)
g << (dist[i] == inf ? 0 : dist[i]) << " ";
return 0;
}