Pagini recente » Cod sursa (job #423656) | Cod sursa (job #2096691) | Cod sursa (job #508858) | Cod sursa (job #1393884) | Cod sursa (job #994572)
Cod sursa(job #994572)
#include <fstream>
#include <vector>
#define INF 1<<30
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
vector <pair<int,int> > G[50002];
int N,M,D[50002],Heap[50002],NHeap,Poz[50002];
bool Use[50002];
void Swap(int X, int Y)
{
swap(Heap[X],Heap[Y]);
swap(Poz[Heap[X]],Poz[Heap[Y]]);
}
void Sift(int X)
{
int Son=(X<<1);
if(Son+1<=NHeap && D[Heap[Son+1]]<D[Heap[Son]])
Son++;
if(Son<=NHeap && D[Heap[Son]]<D[Heap[X]])
{
Swap(Son,X);
Sift(Son);
}
}
void Percolate(int X)
{
int F=X>>1;
if(F && D[Heap[X]]<D[Heap[F]])
{
Swap(X,F);
Percolate(F);
}
}
void Read()
{
int i;
f>>N>>M;
for(i=1;i<=M;i++)
{
int x,y,cost;
f>>x>>y>>cost;
G[x].push_back(make_pair(y,cost));
}
for(i=2;i<=N;i++)
D[i]=INF;
}
void Solve()
{
int i,counter=0;
for(i=1;i<=N;i++)
{
Heap[i]=i;
Poz[i]=i;
}
NHeap=N;
while(counter<N)
{
int pozition=Heap[1];
Swap(1,NHeap);
NHeap--;
Sift(1);
Use[pozition]=1;
counter++;
for(i=0;i<G[pozition].size();i++)
{
int vecin=G[pozition][i].first,cost=G[pozition][i].second;
if(D[pozition]+cost<D[vecin])
{
D[vecin]=D[pozition]+cost;
Percolate(Poz[vecin]);
}
}
}
for(i=2;i<=N;i++)
{
if(D[i]==INF)
D[i]=0;
g<<D[i]<<" ";
}
g<<"\n";
}
int main()
{
Read();
Solve();
return 0;
}