Pagini recente » Cod sursa (job #1086823) | Cod sursa (job #1148001) | Cod sursa (job #1452700) | Cod sursa (job #2609413) | Cod sursa (job #526187)
Cod sursa(job #526187)
#include <algorithm>
#include <vector>
using namespace std;
#define INF 0x3f3f3f3f
#define pb push_back
#define mp make_pair
#define DIM 50005
#define LIM 10005
#define sc second
#define fs first
vector <pair <int,int> > g[DIM];
int dst[DIM],h[DIM],poz[DIM];
int n,m,l,pozitie=LIM-1;
char buff[LIM];
inline void cit (int &nr)
{
char semn;
for (; !isdigit (buff[pozitie]); )
{
semn=buff[pozitie];
if (++pozitie==LIM)
{
fread (buff,1,LIM,stdin);
pozitie=0;
}
}
for (nr=0; isdigit (buff[pozitie]); )
{
nr=nr*10+buff[pozitie]-'0';
if (++pozitie==LIM)
{
fread (buff,1,LIM,stdin);
pozitie=0;
}
}
if (semn=='-')
nr=-nr;
}
void read ()
{
int i,x,y,z;
cit (n); cit (m);
for (i=1; i<=m; ++i)
{
cit (x); cit (y); cit (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;
}