Pagini recente » Cod sursa (job #2060661) | Cod sursa (job #26627) | Cod sursa (job #2942228) | Cod sursa (job #1633716) | Cod sursa (job #856115)
Cod sursa(job #856115)
#include <fstream>
#include <vector>
#include <queue>
#define LS (p<<1)
#define RS ((p<<1)+1)
#define Ft (p>>1)
#define INF (1<<29)
#define NMAX 50004
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int N,M,D[NMAX];
vector<pair<int,int> > V[NMAX];
vector<pair<int,int> >::iterator it,sf;
int Heap[NMAX*10],Size;
bool InHeap[NMAX];
void Down_Heap(int p)
{
int min = p,aux;
if(LS <= Size && D[Heap[LS]] < D[Heap[min]])
min = LS;
if(RS <= Size && D[Heap[RS]] < D[Heap[min]])
min = RS;
if(p != min)
aux = Heap[min],Heap[min] = Heap[p],Heap[p] = aux,Down_Heap(min);
}
void Up_Heap(int p)
{
if(p&&D[Heap[p]] < D[Heap[Ft]])
{
int aux = Heap[p];
Heap[p] = Heap[Ft];
Heap[Ft] = aux;
Up_Heap(Ft);
}
}
void Push_Heap(int nod)
{
if(!InHeap[nod])
Heap[++Size] = nod,Up_Heap(Size),InHeap[nod] = 1;
}
void Pop_Heap()
{
Heap[1] = Heap[Size--];
Down_Heap(1);
}
int main ()
{
int i,x,y,c,n;
in>>N>>M;
while(M--)
{
in>>x>>y>>c;
V[x].push_back(make_pair(y,c));
}
for(D[0] = -1,i=2;i<=N;i++)
D[i] = INF;
Push_Heap(1);
while(Size)
{
x = Heap[1];
InHeap[x] = 0;
Pop_Heap();
for(it=V[x].begin(),sf=V[x].end();it<sf;++it)
{
y = it->first;
c = it->second;
if(D[y] > D[x]+c)
{
D[y] = D[x]+c;
if(!InHeap[y])
Push_Heap(y),InHeap[y] = 1;
}
}
}
for(i=2;i<=N;i++)
out<<(D[i]!= INF ? D[i] : 0)<<' ';
}