Pagini recente » Cod sursa (job #1521654) | Cod sursa (job #1638696) | Cod sursa (job #1923688) | Cod sursa (job #1934172) | Cod sursa (job #526184)
Cod sursa(job #526184)
#include <algorithm>
#include <vector>
using namespace std;
#define INF 0x3f3f3f3f
#define pb push_back
#define mp make_pair
#define DIM 50005
#define sc second
#define fs first
vector <pair <int,int> > g[DIM];
int dst[DIM],h[DIM],poz[DIM];
int n,m,l;
void read ()
{
int i,x,y,z;
scanf ("%d%d",&n,&m);
for (i=1; i<=m; ++i)
{
scanf ("%d%d%d",&x,&y,&z);
g[x].pb (mp (y,z));
}
}
inline void upheap (int nod)
{
int tata;
for ( ; nod>1; )
{
tata=nod>>1;
if (dst[h[tata]]>dst[h[nod]])
{
poz[h[tata]]=nod;
poz[h[nod]]=tata;
swap (h[tata],h[nod]);
nod=tata;
}
else
return ;
}
}
inline void downheap (int nod)
{
int fiu;
for ( ; nod<=l ;)
{
if ((nod<<1)<=l)
{
fiu=nod<<1;
if (fiu+1<=l && dst[h[fiu+1]]<dst[h[fiu]])
++fiu;
}
else
return ;
if (dst[h[nod]]>dst[h[fiu]])
{
poz[h[fiu]]=nod;
poz[h[nod]]=fiu;
swap (h[fiu],h[nod]);
nod=fiu;
}
else
return ;
}
}
void solve ()
{
vector <pair <int,int> > :: iterator it;
int nod;
memset (dst,INF,sizeof (dst));
dst[1]=0;
h[1]=poz[1]=1;
for (l=1; l; )
{
nod=h[1]; h[1]=h[l--]; poz[h[1]]=1; downheap (1);
for (it=g[nod].begin (); it!=g[nod].end (); ++it)
if (dst[nod]+it->sc<dst[it->fs])
{
dst[it->fs]=dst[nod]+it->sc;
if (!poz[it->fs])
poz[h[++l]=it->fs]=l;
upheap (poz[it->fs]);
}
}
}
void print ()
{
int i;
for (i=2; i<=n; ++i)
if (dst[i]==INF)
printf ("0 ");
else
printf ("%d ",dst[i]);
}
int main ()
{
freopen ("dijkstra.in","r",stdin);
freopen ("dijkstra.out","w",stdout);
read ();
solve ();
print ();
return 0;
}