Pagini recente » Rating Alessandro Dogaru (Dogo123) | Cod sursa (job #292231) | Cod sursa (job #1981443) | Cod sursa (job #610169) | Cod sursa (job #554114)
Cod sursa(job #554114)
#include<stdio.h>
#define MAX 50001
#define INF 0x3f3f3f
int X = 1, N, M,order[MAX],D[MAX],P[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);
}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;
P[i] = -1;
order[i] = heap[i].order = i;
}
D[X] = P[X] = 0;
update(X, 0);
}
void make(int x)
{
q = A[x];
while(q)
{
if(q->c + D[x] < D[q->nod])
{
D[q->nod] = q->c + D[x];
P[q->nod] = x;
}
q = q->next;
}
}
int main()
{
FILE*f = fopen("dijkstra.in","r");
fscanf(f,"%d%d",&N,&M);
init();
int i,A,B,C,p;
for(i=1;i<=M;++i)
{
fscanf(f,"%d%d%d",&A,&B,&C);
if(A == X)
{
D[B] = C;
P[B] = A;
update(order[B], C);
}
if(B == X)
{
D[A] = C;
P[A] = B;
update(order[A], C);
}
add(A,B,C);
add(B,A,C);
}
fclose(f);
while(nrelem)
{
p = heap[1].order;
cut(1);
make(p);
}
FILE*g = fopen("dijkstra.out","w");
for(i=2;i<=N;++i)
{
if(D[i] == INF)D[i] = 0;
fprintf(g,"%d ",D[i]);
}
fclose(g);
return 0;
}