Pagini recente » Borderou de evaluare (job #2085087) | Cod sursa (job #1274146) | Cod sursa (job #541011) | Cod sursa (job #1109237) | Cod sursa (job #594291)
Cod sursa(job #594291)
#include <fstream>
#include <vector>
using namespace std;
struct edge
{
int dest,cost;
};
const long Infinit=2000000005;
vector <edge> G[50005];
long D[50005], Heap[50005], P[50005], NH;
unsigned long N;
void Read ()
{
ifstream fin ("dijkstra.in");
long M, X, Y, Z;
edge aux;
fin >> N >> M;
for (; M>0; --M)
{
fin >> X >> Y >> Z;
aux.dest=Y;
aux.cost=Z;
G[X].push_back (aux);
}
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].dest]==-1)
{
D[G[NCurent][i].dest]=D[NCurent]+G[NCurent][i].cost;
Insert (G[NCurent][i].dest);
}
if (D[G[NCurent][i].dest]>D[NCurent]+G[NCurent][i].cost)
{
D[G[NCurent][i].dest]=D[NCurent]+G[NCurent][i].cost;
Percolate (P[G[NCurent][i].dest]);
}
}
}
}
int main()
{
Read ();
Dijkstra (1);
Type ();
return 0;
}