Pagini recente » Cod sursa (job #1743123) | Cod sursa (job #630124) | Cod sursa (job #439665) | Cod sursa (job #1003826) | Cod sursa (job #399699)
Cod sursa(job #399699)
#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));
}
}
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 ;
}
}
void downheap (int nod)
{
int fiu;
for ( ; nod<=l; )
{
if ((nod<<1)<=l)
{
if ((nod<<1)+1<=l)
if (dst[h[fiu]]<dst[h[fiu+1]])
++fiu;
}
else
return ;
if (dst[h[fiu]]<dst[h[nod]])
{
poz[h[fiu]]=nod;
poz[h[nod]]=fiu;
swap (h[nod],h[fiu]);
nod=fiu;
}
else
return ;
}
}
void solve ()
{
int nod,i;
memset (dst,INF,sizeof (dst));
for (dst[1]=0, poz[h[l=1]=1]=1; l; )
{
nod=h[1];
h[1]=h[l--];
poz[h[1]]=1;
downheap (1);
for (i=0; i<(int)g[nod].size (); ++i)
if (dst[nod]+g[nod][i].sc<dst[g[nod][i].fs])
{
dst[g[nod][i].fs]=dst[nod]+g[nod][i].sc;
if (poz[g[nod][i].fs])
upheap (poz[g[nod][i].fs]);
else
{
poz[h[++l]=g[nod][i].fs]=l;
upheap (l);
}
}
}
}
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;
}