Pagini recente » Cod sursa (job #2173310) | Cod sursa (job #785692) | Cod sursa (job #1601880) | Cod sursa (job #94061) | Cod sursa (job #3311613)
#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
using namespace std;
//ifstream cin("dijkstra.in");
//ofstream cout("dijkstra.out");
const int NMAX=5e4+5, MMAX=25e4+5, INF=1e9;
int n, m, dist[NMAX], viz[NMAX], npq;
struct edge
{
int v, c;
friend bool operator>(const edge a, const edge b)
{
return a.c>b.c;
}
}pq[2*MMAX];
vector<edge> adj[NMAX];
priority_queue<edge> pqq;
void insert(edge val)
{
pq[++npq]=val;
int cn=npq;
while(cn>1 && pq[cn/2]>pq[cn])
{
swap(pq[cn/2], pq[cn]);
cn/=2;
}
}
void pop()
{
swap(pq[1], pq[npq]);
npq--;
int cn=1;
while((2*cn<=npq && pq[cn]>pq[2*cn]) || (2*cn+1<=npq && pq[cn]>pq[2*cn+1]))
{
edge maxv={0, INF};
int maxn;
if(2*cn<=npq && maxv>pq[2*cn])
{
maxv=pq[2*cn];
maxn=2*cn;
}
if(2*cn+1<=npq && maxv>pq[2*cn+1])
{
maxv=pq[2*cn+1];
maxn=2*cn+1;
}
swap(pq[cn], pq[maxn]);
cn=maxn;
}
}
edge top()
{
return pq[1];
}
void Dijkstra()
{
insert({1, 0}); dist[1]=0;
while(npq)
{
edge u=top(); pop();
if(viz[u.v])
continue;
viz[u.v]=1;
for(auto e:adj[u.v])
if(u.c+e.c<dist[e.v])
{
dist[e.v]=u.c+e.c;
insert({e.v, dist[e.v]});
}
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
dist[i]=INF;
while(m--)
{
int a, b, c;
cin>>a>>b>>c;
adj[a].push_back({b, c});
}
Dijkstra();
for(int i=2;i<=n;i++)
cout<<((dist[i]==INF)?0:dist[i])<<" ";
return 0;
}