Pagini recente » Cod sursa (job #1867382) | Cod sursa (job #3242338) | Cod sursa (job #210429) | Cod sursa (job #657) | Cod sursa (job #594288)
Cod sursa(job #594288)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const long Infinit=2000000005;
vector <long> G[50005];
vector <long> C[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 (Y);
C[X].push_back (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 ();
}
void Sift (long X)
{
long S=X<<1,Aux;
while (S<=NH)
{
if (((X<<1)+1<=NH)&&(D[Heap[S]]>D[Heap[(X<<1)+1]]))
{
S++;
}
if (D[Heap[S]]<D[Heap[X]])
{
Aux=P[Heap[X]];
P[Heap[X]]=P[Heap[S]];
P[Heap[S]]=Aux;
Aux=Heap[X];
Heap[X]=Heap[S];
Heap[S]=Aux;
X=S;
S=X<<1;
}
else
{
return;
}
}
}
void Percolate (long X)
{
long F=X>>1,Aux;
while (F!=0)
{
if ((D[Heap[F]]>D[Heap[X]])&&(F>0))
{
Aux=P[Heap[X]];
P[Heap[X]]=P[Heap[F]];
P[Heap[F]]=Aux;
Aux=Heap[X];
Heap[X]=Heap[F];
Heap[F]=Aux;
X=F;
F=X>>1;
}
else
{
return;
}
}
}
inline void Insert (long X)
{
Heap[++NH]=X;
P[Heap[NH]]=NH;
Percolate (NH);
}
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];
Heap[1]=Heap[NH--];
P[Heap[1]]=1;
Sift (1);
for (i=0; i<G[NCurent].size (); ++i)
{
if (P[G[NCurent][i]]==-1)
{
D[G[NCurent][i]]=D[NCurent]+C[NCurent][i];
Insert (G[NCurent][i]);
}
if (D[G[NCurent][i]]>D[NCurent]+C[NCurent][i])
{
D[G[NCurent][i]]=D[NCurent]+C[NCurent][i];
Percolate (P[G[NCurent][i]]);
}
}
}
}
int main()
{
Read ();
Dijkstra (1);
Type ();
return 0;
}