Pagini recente » Cod sursa (job #1685458) | Cod sursa (job #1027982) | Cod sursa (job #1214130) | Cod sursa (job #1628023) | Cod sursa (job #596275)
Cod sursa(job #596275)
#include <iostream>
#include <fstream>
#include <vector>
#define V first
#define C second
using namespace std;
const long Infinit=2000000005;
vector < pair <long, long > > G[50005];
long D[50005], Heap[50005], P[50005], NH;
unsigned long N;
void Read ()
{
ifstream fin ("dijkstra.in");
long M, X, Y, Z;
fin >> N >> M;
for (; M>0; --M)
{
fin >> X >> Y >> Z;
G[X].push_back (make_pair (Y, Z));
}
fin.close ();
}
void Type ()
{
ofstream fout ("dijkstra.out");
unsigned long i;
for (i=2; i<=N; ++i)
{
if (D[i]==Infinit)
{
D[i]=0;
}
fout << D[i] << " ";
}
fout << "\n";
fout.close ();
}
inline void Swap (long X, long Y)
{
long Aux;
Aux=P[Heap[X]];
P[Heap[X]]=P[Heap[Y]];
P[Heap[Y]]=Aux;
Aux=Heap[X];
Heap[X]=Heap[Y];
Heap[Y]=Aux;
}
void Sift (long X)
{
long S=2*X;
while (S<=NH)
{
if ((2*X+1<=NH)&&(D[Heap[S]]>D[Heap[2*X+1]]))
{
S++;
}
if (D[Heap[S]]<D[Heap[X]])
{
Swap (X, S);
X=S;
S=2*X;
}
else
{
return;
}
}
}
void Percolate (long X)
{
long F=X/2;
while (F!=0)
{
if ((D[Heap[F]]>D[Heap[X]])&&(F>0))
{
Swap (X, F);
X=F;
F=X/2;
}
else
{
return;
}
}
}
inline void Insert (long X)
{
Heap[++NH]=X;
P[Heap[NH]]=NH;
Percolate (NH);
}
inline void Delete (long X)
{
Heap[X]=Heap[NH--];
P[Heap[X]]=1;
Sift (X);
}
void Dijkstra (long Start)
{
unsigned long i;
long NCurent;
for (i=1; i<=N; ++i)
{
P[i]=-1;
D[i]=Infinit;
}
D[Start]=0;
P[Start]=1;
Heap[++NH]=Start;
while (NH>0)
{
NCurent=Heap[1];
Delete (1);
for (i=0; i<G[NCurent].size (); ++i)
{
if (P[G[NCurent][i].V]==-1)
{
D[G[NCurent][i].V]=D[NCurent]+G[NCurent][i].C;
Insert (G[NCurent][i].V);
}
if (D[G[NCurent][i].V]>D[NCurent]+G[NCurent][i].C)
{
D[G[NCurent][i].V]=D[NCurent]+G[NCurent][i].C;
Percolate (P[G[NCurent][i].V]);
}
}
}
}
int main()
{
Read ();
Dijkstra (1);
Type ();
return 0;
}