Pagini recente » Cod sursa (job #3358900) | Cod sursa (job #2148177) | Monitorul de evaluare | Monitorul de evaluare | Cod sursa (job #2532798)
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
const int nax = 50005;
const int inf = (1<<30);
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int D[nax];
bool InCoada[nax];
int n, m;
vector<pair<int, int>> G[nax];
struct compara
{
bool operator()(int x, int y)
{
return D[x] < D[y];
}
};
priority_queue<int, vector<int>, compara> Coada;
void Read()
{
int x, y, cost;
f >> n >> m;
for(int i = 1; i <= m; ++i)
{
f >> x >> y >> cost;
G[x].pb(make_pair(y, cost));
}
}
void Dijkstra(int nodStart)
{
for(int i = 1; i <= n; ++i)
D[i] = inf;
D[nodStart] = 0;
Coada.push(nodStart);
InCoada[nodStart] = true;
while(!Coada.empty())
{
int nodCurent = Coada.top();
Coada.pop();
InCoada[nodCurent] = false;
for(size_t i = 0; i < G[nodCurent].size(); ++i)
{
int Vecin = G[nodCurent][i].first;
int Cost = G[nodCurent][i].second;
if(D[nodCurent] + Cost < D[Vecin])
{
D[Vecin] = D[nodCurent] + Cost;
if(!InCoada[Vecin])
{
Coada.push(Vecin);
InCoada[Vecin] = true;
}
}
}
}
}
void Write()
{
for(int i = 2; i <= n; ++i)
{
if(D[i] != inf)
g << D[i] << " ";
else
g << "0 ";
}
}
int main()
{
ios::sync_with_stdio(false);
Read();
Dijkstra(1);
Write();
return 0;
}