Pagini recente » Cod sursa (job #516737) | Cod sursa (job #2547548) | Cod sursa (job #1516170) | Cod sursa (job #640638) | Cod sursa (job #2218112)
#include <iostream>
#include <fstream>
#define dim 50001
using namespace std;
const int inf = 2000000000; ///infinit
ifstream fin ("dijkstra.in");
ofstream fout ("dijkstra.out");
struct graf
{
int nod,len;
graf* next;
}*a[dim];
int n,m,H[dim],d[dim],poz[dim];
inline int father(int nod)
{
return nod / 2;
}
inline int left_son(int nod)
{
return nod * 2;
}
inline int right_son(int nod)
{
return nod * 2 + 1;
}
inline int mini_heap()
{
return H[1];
}
void sift(int N, int K)
{
int son;
do
{
son = 0;
// Alege un fiu mai mare ca tatal.
if (left_son(K) <= N)
{
son = left_son(K);
if (right_son(K) <= N && d[H[right_son(K)]] < d[H[left_son(K)]])
{
son = right_son(K);
}
if (d[H[son]] >= d[H[K]])
{
son = 0;
}
}
if (son)
{
swap(H[K], H[son]);
swap(poz[H[K]],poz[H[son]]);
K = son;
}
}
while (son);
}
void percolate(int N, int K)
{
int key = H[K];
int aux = poz[H[K]];
while ((K > 1) && (d[key] < d[H[father(K)]]))
{
H[K] = H[father(K)];
poz[H[K]]=poz[H[father(K)]];
K = father(K);
}
H[K] = key;
poz[H[K]]=aux;
}
void cut(int& N, int K)
{
H[K] = H[N];
poz[H[K]] = poz[H[N]];
--N;
if ((K > 1) && (d[H[K]] > d[H[father(K)]]))
{
percolate(N, K);
}
else
{
sift(N, K);
}
}
void build_heap(int N)
{
for (int i = N / 2; i > 0; --i)
{
sift(N, i);
}
}
void afisare(int a[])
{
for (int i=1; i<=n; i++)
cout<<a[i]<<' ';
cout<<'\n';
}
void afisare(bool a[])
{
for (int i=1; i<=n; i++)
cout<<a[i]<<' ';
cout<<'\n';
}
int main()
{
fin>>n>>m;
for (int i=0; i<m; i++)
{
int x,y,cost;
fin>>x>>y>>cost;
graf* nou=new graf;
nou->nod=y;
nou->len=cost;
nou->next=a[x];
a[x]=nou;
}
d[1]=0;
H[1]=1;
poz[1]=1;
for (int i=2; i<=n; i++)
d[i]=inf,H[i]=i,poz[i]=i;
graf* i=a[1];
while(i!=NULL)
{
d[i->nod]=i->len;
i=i->next;
}
build_heap(n);
int auxn=n;
while (n)
{
int nodcurent=mini_heap();
cut(n,1);
graf* j=a[nodcurent];
while (j!=NULL)
{
if (d[nodcurent]+j->len<d[j->nod])
{
d[j->nod]=d[nodcurent]+j->len;
percolate(n,poz[j->nod]);
}
j=j->next;
}
}
for (int i=2; i<=auxn; i++)
{
if (d[i]==inf)
d[i]=0;
fout<<d[i]<<' ';
}
//afisare(d);
//afisare(s);
//afisare(t);
return 0;
}