Pagini recente » Cod sursa (job #1225564) | Monitorul de evaluare | Istoria paginii utilizator/thegamer1023 | Cod sursa (job #1035814) | Cod sursa (job #676879)
Cod sursa(job #676879)
#include<fstream>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
typedef struct nod{int vecin,cost;
nod *next;
};
int n,m,d[50001],h[50001],poz[50001],k;
nod *v[50001],*q;
inline void citire()
{int a,b,c,i;
fin >> n >> m;
for (i=1;i<=m;++i)
{ fin >> a >> b >> c;
q = new nod;
q->next = v[a];
q->cost = c;
q->vecin = b;
v[a] = q;
}
}
inline void upheap(int x)
{int tata;
while (x>1)
{ tata = x>>1;
if (d[h[tata]] > d[h[x]])
{ poz[h[x]] = tata;
poz[h[tata]] = x;
h[tata] = h[tata] + h[x] - (h[x] = h[tata]);
x = tata;
}
else
return ;
}
}
inline void downheap(int x)
{int fiu;
while (x<=k)
{ fiu = x;
if ((x<<1) <= k)
{ fiu = x << 1;
if ((fiu+1 <= k) && d[h[fiu+1] < d[fiu]])
++fiu;
}
else
return ;
if (d[h[x]] > d[h[fiu]])
{ poz[h[x]] = fiu;
poz[h[fiu]] = x;
h[x] = h[x] + h[fiu] -(h[fiu] - h[x]);
}
else return ;
}
}
inline void dijkstra()
{int i,min1;
for (i=2;i<=n;++i)
{ d[i] = 1073741824;
poz[i] = -1;
}
poz[1] = 1;
h[++k] = 1;
while (k)
{ min1 = h[1];
h[1] = h[1] + h[k] - (h[k] = h[1]);
poz[h[1]] = 1;
--k;
downheap(1);
q = v[min1];
while (q)
{ if (d[q->vecin] > d[min1] + q->cost)
{ d[q->vecin] = d[min1] + q->cost;
if (poz[q->vecin] != -1)
upheap(poz[q->vecin]);
else
{ h[++k] = q-> vecin;
poz[h[k]] = k;
upheap(k);
}
}
q = q->next;
}
}
}
int main()
{int i;
citire();
dijkstra();
for (i=2;i<=n;++i)
fout << d[i] << " ";
return 0;
}