Pagini recente » Cod sursa (job #69415) | Cod sursa (job #1718493) | Cod sursa (job #3138429) | Cod sursa (job #941161) | Cod sursa (job #1587927)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50002
#define INF 999999999
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
struct graf
{
int nod,c;
}pc,cod;
int n,m,grad,x,y,cost;
vector<graf> a[NMAX];
graf heap[NMAX];
int d[NMAX];
struct comp{
bool operator() (graf a, graf b)
{
if(a.c < b.c)
return true;
return false;
}
};
void sus(int x)
{
while(heap[x/2].c>heap[x].c && x>1)
{
swap(heap[x/2],heap[x]);
x = x/2;
}
}
void jos(int x)
{
while((heap[x].c > heap[x*2+1].c && x*2+1<=grad) || (heap[x].c>heap[x*2].c && x*2<=grad))
{
if(heap[x*2].c > heap[x*2+1].c && x*2+1<=grad)
{
swap(heap[x],heap[x*2+1]);
// x = x*2+1;
}
else if(x*2<=grad)
{
swap(heap[x],heap[x*2]);
//x = x*2;
}
}
}
graf Min()
{
graf M = heap[1];
if(grad>0)
heap[1] = heap[grad--];
jos(1);
return M;
}
void Insert(graf a)
{
heap[++grad] = a;
sus(grad);
}
//void dijkstra()
//{
//
// for(int i=2;i<=n;i++)
// d[i] = INF;
// pc.c = 0; pc.nod = 1;
// Insert(pc);
// coada.push(pc);
// while(grad!=0)
// while(!coada.empty())
// {
//
// pc = Min();
// pc = coada.top(); coada.pop();
//
// for(int i=0;i<a[pc.nod].size();i++)
// {
// cout << pc.c;
// if(d[a[pc.nod][i].nod] > pc.c + a[pc.nod][i].c)
// {
//
// d[a[pc.nod][i].nod] = pc.c + a[pc.nod][i].c;
// cod.c = d[a[pc.nod][i].nod];
// cod.nod = a[pc.nod][i].nod;
// Insert(cod);
// coada.push(cod);
// }
// }
// }
//}
void dijkstra1()
{
for(int i=2;i<=n;i++)
d[i] = INF;
priority_queue<graf, vector<graf> ,comp> T;
int nods,costs,di,val,x;
pc.c = 0;
pc.nod =1;
T.push(pc);
while(!T.empty())
{
val = T.top().c;
x = T.top().nod;
T.pop();
di = a[x].size();
for(int i=0;i<di;++i)
{
if(d[a[x][i].nod]> val + a[x][i].c)
{
d[a[x][i].nod]= val + a[x][i].c;
pc.c = d[a[x][i].nod];
pc.nod = a[x][i].nod;
T.push(pc);
}
}
}
}
int main()
{
in >> n >> m;
for(int i=1;i<=m;i++)
{
in >> x >> y >> cost;
pc.nod = y;
pc.c = cost;
a[x].push_back(pc);
}
dijkstra1();
for(int i=2;i<=n;i++)
if(d[i]!=INF)
out << d[i] << " ";
else
out << 0 << " ";
return 0;
}