Pagini recente » Cod sursa (job #3296067) | Cod sursa (job #3139181) | Cod sursa (job #3224638) | Cod sursa (job #3279974) | Cod sursa (job #751230)
Cod sursa(job #751230)
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
using namespace std;
typedef pair<int, int> pr;
const int N_MAX=50011;
const int oo=1<<29;
int lHeap;
vector<pr> G[N_MAX];
vector<pr>::const_iterator it, iend;
int d[N_MAX], H[N_MAX], P[N_MAX];
inline void _swap(int& x, int& y) {int aux=x; x=y; y=aux;}
void DownHeap(int k)
{
for(int son=k<<1; son <= lHeap; k=son, son<<=1)
{
if(son < lHeap && d[H[son]] > d[H[son+1]] )
++son;
if(d[H[k]] <= d[H[son]])
return;
_swap(H[k], H[son]);
P[H[k]]=k;
P[H[son]]=son;
}
}
void UpHeap(int k)
{
for(int key=d[H[k]], f=k>>1; k > 1 && key < d[H[f]]; k=f, f>>=1)
{
_swap(H[k], H[f]);
P[H[f]]=f;
P[H[k]]=k;
}
}
inline void push(int x)
{
H[++lHeap]=x;
P[x]=lHeap;
UpHeap(lHeap);
}
inline int pop()
{
int r=H[1];
P[H[1]]=-1;
H[1]=H[lHeap];
P[H[1]]=1;
--lHeap;
DownHeap(1);
return r;
}
int main()
{
int N, M, x, y, c;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
for(in>>N>>M; M; --M)
{
in>>x>>y>>c;
G[x].push_back(pr(y,c));
}
fill(d, d+N+1, oo);
d[1]=0;
for(push(1); lHeap; )
{
x=pop();
P[x]=-1;
for(it=G[x].begin(), iend=G[x].end(); it < iend; ++it)
{
if(-1 == P[it->first])
continue;
if(oo == d[it->first])
{
d[it->first]=d[x]+it->second;
push(it->first);
}
else if(d[it->first] > d[x] + it->second)
{
d[it->first]=d[x]+it->second;
UpHeap(P[it->first]);
}
}
}
replace(d+1, d+N+1, oo, 0);
copy(d+2, d+N+1, ostream_iterator<int>(out, " "));
out<<"\n";
return EXIT_SUCCESS;
}