Pagini recente » Cod sursa (job #1863259) | Cod sursa (job #8238) | Cod sursa (job #1828279) | Cod sursa (job #3130726) | Cod sursa (job #554135)
Cod sursa(job #554135)
#include<fstream>
#define MAX 50001
#define INF 0x3f3f3f
using namespace std;
int X = 1, N, M,order[MAX],D[MAX],nrelem;
struct HEAP
{
int val,order;
}heap[MAX],aux;
struct graf
{
int nod,c;
graf*next;
}*A[MAX],*q;
void add(int x,int y,int c)
{
q = new graf;
q->nod = y;
q->c = c;
q->next = A[x];
A[x] = q;
}
int left_son(int x){return 2*x;}
int right_son(int x){return 2*x+1;}
int father(int x){return x/2;}
void swap(int x,int y)
{
order[heap[x].order] = y;
order[heap[y].order] = x;
aux = heap[x];
heap[x] = heap[y];
heap[y] = aux;
}
void sift(int x)
{
int son;
do
{
son = 0;
if(left_son(x)<=nrelem)
{
son = left_son(x);
if(right_son(x)<=nrelem && heap[right_son(x)].val < heap[son].val)
son = right_son(x);
}
if(heap[x].val <= heap[son].val)
son = 0;
if(son)
{
swap(x,son);
x = son;
}
}while(son);
}
void percolate(int x)
{
while(father(x) && heap[father(x)].val > heap[x].val)
{
swap(x,father(x));
x = father(x);
}
}
void cut(int x)
{
heap[x] = heap[nrelem--];
sift(x);
if(father(x) && heap[father(x)].val > heap[x].val)
percolate(x);
}
void update(int x,int val)
{
heap[x].val = val;
sift(x);
if(father(x) && heap[father(x)].val > heap[x].val)
percolate(x);
}
void init()
{
int i;
nrelem = N;
for(i=1;i<=N;++i)
{
D[i] = heap[i].val = INF;
order[i] = heap[i].order = i;
}
D[X] = 0;
update(X, 0);
cut(order[X]);
}
void make(int x)
{
q = A[x];
while(q)
{
if(q->c + D[x] < D[q->nod])
{
D[q->nod] = q->c + D[x];
update(order[q->nod], D[q->nod]);
}
q = q->next;
}
}
int main()
{
ifstream f("dijkstra.in");
f>>N>>M;
init();
int i,A,B,C,p;
for(i=1;i<=M;++i)
{
f>>A>>B>>C;
if(A == X)
{
D[B] = C;
update(order[B], C);
}
else add(A,B,C);
}
f.close();
i = 1;
while(i <= N)
{
if(heap[1].val == INF)
{i = N+1;continue;}
p = heap[1].order;
cut(1);
make(p);
++i;
}
ofstream g("dijkstra.out");
for(i=2;i<=N;++i)
{
if(D[i] == INF)D[i] = 0;
g<<D[i]<<" ";
}
g.close();
return 0;
}