Mai intai trebuie sa te autentifici.

Cod sursa(job #154080)

Utilizator oumbraPaul Filimoon oumbra Data 10 martie 2008 21:51:55
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <cstdio>
#include <cstdlib>
#include <cstring>

#define SIZE 50005

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

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

struct nod 
{
	long long dest, c;

	struct nod * next;
};

struct nod * nds[SIZE];

void add(long long from, long long to, long long 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()
{	
	long long 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(long long 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;	
}

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

	return nodq;
}

int main()
{
	long long 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;
}