Pagini recente » Cod sursa (job #2548532) | Cod sursa (job #912664) | Cod sursa (job #2275289) | Cod sursa (job #2085276) | Cod sursa (job #2397049)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int NMAX=50005;
const int HeapMax=500005;
const int oo=2000000000;
vector < pair < int, int > > T[NMAX];
int Distante[NMAX],Heap[HeapMax],L;
bool Viz[NMAX];
int N,M;
inline void swap(int a, int b)
{
int aux=Heap[a];
Heap[a]=Heap[b];
Heap[b]=aux;
}
void upheap(int x)
{
int tata=x/2;
if (tata!=0&&Heap[x]<Heap[tata])
{
swap(x,tata);
upheap(tata);
}
}
void downheap(int x)
{
int fiu;
int fiu_st=x*2;
int fiu_dr=x*2+1;
if (fiu_dr<=L&&Heap[fiu_dr]<Heap[fiu_st])
fiu=fiu_dr;
else fiu=fiu_st;
if (fiu<=L && Heap[fiu]<Heap[x])
{
swap(fiu,x);
downheap(fiu);
}
}
void heap_insert(int x)
{
L++;
Heap[L]=x;
upheap(L);
}
void pop()
{
swap(1,L);
--L;
if (L>0)
downheap(1);
}
int main()
{
fin>>N>>M;
for (int i=1; i<=M; i++)
{
int x,y,cost;
fin>>x>>y>>cost;
T[x].push_back(make_pair(y,cost));
}
for (int i=1; i<=N; i++)
Distante[i]=oo;
Distante[1]=0;
heap_insert(1);
Viz[1]=true;
while (L>0)
{
int Nod=Heap[1];
pop();
Viz[Nod]=false;
for (unsigned int i=0; i<T[Nod].size(); i++)
{
int Vecin=T[Nod][i].first;
int Cost=T[Nod][i].second;
if (Distante[Nod]+Cost<Distante[Vecin])
{
Distante[Vecin]=Distante[Nod]+Cost;
if (!Viz[Vecin])
{
heap_insert(Vecin);
Viz[Vecin]=true;
}
}
}
}
for (int i=2; i<=N; i++)
if (Distante[i]==oo)
fout<<"0 ";
else fout<<Distante[i]<<" ";
return 0;
}