Cod sursa(job #154081)

Utilizator oumbraPaul Filimoon oumbra Data 10 martie 2008 21:53:41
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <cstdio>
#include <cstdlib>
#include <cstring>

#define SIZE 50005

int heap[SIZE], heapSize;
char inQ[SIZE];
int d[SIZE], dheap[SIZE];
int n, m;

struct queue 
{
	int nod;
	struct queue * next;
};

struct nod 
{
	int dest, c;

	struct nod * next;
};

struct nod * nds[SIZE];

void add(int from, int to, int c)
{
	struct nod * cnod;

	cnod = (nod *) malloc(sizeof(struct nod));

	cnod->dest = to;
	cnod->c = c;	
	cnod->next = nds[from];

	nds[from] = cnod;

}

void read()
{	
	int i, t1, t2, t3;

	freopen("dijkstra.in", "r", stdin);
	freopen("dijkstra.out", "w", stdout);

	scanf("%lld%lld", &n, &m);

	for(i = 0; i < m; i++)
	{
		scanf("%lld%lld%lld", &t1, &t2, &t3);

		add(t1, t2, t3);
//		add(t2, t1, t3);
	}
	
}

struct queue * q;
struct queue * cq;

void addq(int nod)
{
	struct queue * newq = (struct queue *)  malloc(sizeof(struct queue));

	newq->nod = nod;
	newq->next = NULL;

	if(q == NULL)
	{
		cq = newq;
		q = cq;
	}
	else
	{
		cq->next = newq;

		cq = cq->next;
	}

	inQ[nod] = 1;	
}

int getq()
{
	int nodq = q->nod;
	inQ[nodq] = 0;
	q = q->next;

	return nodq;
}

int main()
{
	int i, j, from;
	
//	q = (struct queue *) malloc(sizeof(struct queue));
	cq = q = NULL;

	read();

	for(i = 1; i <= n; i++)
		d[i] = 1 << 30;

	d[1] = 0;

	addq(1);

	struct nod * cnod;

	while(q)
	{
		i = getq();
		cnod = nds[i];

		//cnod = nds[i];
		
		while(cnod)
		{
			if(d[cnod->dest] > d[i] + cnod->c)
			{
				if(!inQ[cnod->dest])
				{
					addq(cnod->dest);
				}
		
				d[cnod->dest] = d[i] + cnod->c;
			}

			cnod = cnod->next;
		}
	}
/*
	for(i = 1; i <= n; i++)
	{
		fprintf(stderr, "%d ", d[i]);
	}
	fprintf(stderr, "\n\n");
*/
	

	for(i = 2; i <= n; i++)
	{
		d[i] == 1 << 30 ? printf("0 ") : printf("%lld ", d[i]);
	}

	return 0;
}