Pagini recente » Cod sursa (job #2823848) | Cod sursa (job #1501725) | Cod sursa (job #546520) | Cod sursa (job #769085) | Cod sursa (job #771164)
Cod sursa(job #771164)
#include <fstream>
#include <vector>
#include <algorithm>
#define NLen 0x10000
#define inf 0x7fffffff
using namespace std;
ifstream fi;
ofstream fo;
vector < pair < int, int > > G[NLen];
int DIST[NLen];
int h[NLen];
int pos[NLen];
int N;
inline void Up_Heap(int nod)
{
int Old = h[nod];
for(; nod > 1 && DIST[ h[nod >> 1] ] > DIST[Old]; )
{
h[nod] = h[nod >> 1];
pos[ h[nod] ] = nod;
nod >>= 1;
}
h[nod] = Old;
pos[Old] = nod;
}
inline void Down_Heap(int nod)
{
int L, R, Old = h[nod];
while(1)
{
L = nod << 1;
R = L + 1;
if(R <= h[0] && DIST[ h[L] ] > DIST[ h[R] ] && DIST[ h[R] ] < DIST[Old])
{
h[nod] = h[R];
pos[ h[nod] ] = nod;
nod = R;
}
else
if(L <= h[0] && DIST[ h[L] ] < DIST[Old])
{
h[nod] = h[L];
pos[ h[nod] ] = nod;
nod = L;
}
else
{
h[nod] = Old;
pos[Old] = nod;
return;
}
}
}
inline void Pop_Heap(int nod)
{
if(h[0] == nod)
{
-- h[0];
return;
}
h[nod] = h[ h[0] -- ];
pos[ h[nod] ] = nod;
if(nod > 1 && DIST[ h[nod >> 1] ] > DIST[ h[nod] ]) Up_Heap(nod);
else Down_Heap(nod);
}
inline void dij(int nod)
{
for(int i=1;i<=N;++i)
{
DIST[i] = inf;
h[i] = i;
pos[i] = i;
}
DIST[nod] = 0;
h[0] = N;
pos[1] = nod;
pos[nod] = 1;
h[nod] = 1;
h[1] = nod;
while(h[0])
{
nod = h[1];
Pop_Heap(1);
for(unsigned int i = 0; i < G[nod].size(); ++ i)
if(DIST[ G[nod][i].first ] == inf || DIST[ G[nod][i].first ] > DIST[nod] + G[nod][i].second)
{
DIST[ G[nod][i].first ] = DIST[nod] + G[nod][i].second;
Up_Heap(pos[ G[nod][i].first ]);
}
}
}
int main()
{
int M, x, y, c;
fi.open("dijkstra.in");
fi >> N >> M;
for(; M -- ; )
{
fi >> x >> y >> c;
G[x].push_back(make_pair(y, c));
}
fi.close();
dij(1);
fo.open("dijkstra.out");
for(int i = 2; i <= N; ++ i)
if(DIST[i] == inf) DIST[i] = 0;
for(int i = 2; i <= N; ++ i) fo << DIST[i] << ' ';
fo << '\n';
fo.close();
return 0;
}