Pagini recente » Cod sursa (job #2878436) | Cod sursa (job #1225675) | Cod sursa (job #2933807) | Cod sursa (job #829924) | Cod sursa (job #2869798)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
typedef pair < int, int > PII;
const int NMAX = 5e4 + 1;
const int Source = 1;
const int INF = 1e9;
int N;
vector < PII > G[NMAX];
int d[NMAX];
bool Sel[NMAX];
auto cmp = [] (PII A, PII B)
{
if(!(A.first < B.first))
return 1;
return 0;
};
priority_queue < PII, vector < PII >, decltype(cmp) > H(cmp);
static inline void Read ()
{
f.tie(nullptr);
int M = 0;
f >> N >> M;
for(int i = 1; i <= M; ++i)
{
int x = 0, y = 0, c = 0;
f >> x >> y >> c;
G[x].push_back({c, y});
}
return;
}
static inline void Initialize (int X)
{
for(int i = 1; i <= N; ++i)
if(i == X)
d[i] = 0, Sel[i] = true;
else
d[i] = INF, Sel[i] = false;
return;
}
static inline void Expand (int Node)
{
for(auto it : G[Node])
if(it.first < d[it.second])
d[it.second] = it.first, H.push(it);
return;
}
static inline void Dijkstra (int Start)
{
Initialize(Start);
Expand(Start);
while(!H.empty())
{
while(!H.empty() && Sel[H.top().second])
H.pop();
if(H.empty())
break;
PII Top = H.top();
H.pop();
int Dist = Top.first, Node = Top.second;
Sel[Node] = 1;
for(auto it : G[Node])
if(Dist + it.first < d[it.second])
d[it.second] = Dist + it.first, H.push({d[it.second], it.second});
}
return;
}
int main()
{
Read();
Dijkstra(Source);
for(int i = 2; i <= N; ++i)
{
g << (d[i] == INF ? 0 : d[i]);
if(i != N)
g << ' ';
}
g << '\n';
return 0;
}