Pagini recente » Cod sursa (job #517549) | Cod sursa (job #1782052) | Cod sursa (job #2469569) | Cod sursa (job #1830772) | Cod sursa (job #3224769)
#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;
int fr[nmax], n, m, cost[nmax];
vector< pair<int, int> > a[nmax];
priority_queue< pair<int, int> > Q;
int findMin()
{
while(!Q.empty() && fr[Q.top().second])
Q.pop();
if(Q.empty())
return -1;
int nod = Q.top().second;
Q.pop();
return nod;
}
void Dij()
{
for(int i = 2; i <= n; i ++)
cost[i] = inf;
Q.push({0, 1});
for(int i = 1; i <= n; i ++)
{
int nod = findMin();
if(nod == -1)
return;
fr[nod] = 1;
for(int j = 0; j < a[nod].size(); j ++)
{
int x = a[nod][j].first;
int c = a[nod][j].second;
if(c + cost[nod] < cost[x])
{
cost[x] = cost[nod] + c;
Q.push({-cost[x], x});
}
}
}
}
int main()
{
f >> n >> m;
for(int i = 1; i <= n; i ++)
{
int x, y, c;
f >> x >> y >> c;
a[x].push_back({y, c});
}
for(int i = 2; i <= n; i ++)
cost[i] = inf;
Dij();
for(int i = 2; i <= n; i ++)
if(cost[i] == inf)
g << 0 << " ";
else
g << cost[i] << " ";
return 0;
}