Cod sursa(job #702909)

Utilizator hunter_ionutzzzFarcas Ionut hunter_ionutzzz Data 2 martie 2012 10:03:06
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include<cstdio>
#include<fstream>
using namespace std;
FILE *fin=fopen("dijkstra.in","r");
ofstream fout("dijkstra.out");
const int inf = 1 << 30;
const int lung = 50001;
struct nod{int val,cost;
                    nod *next;
};
int h[lung],d[lung],poz[lung],k,i,n,m,a,b,cost;
nod *q,*v[lung];

inline void upheap(int x)
{int tata;
    while (x > 1)
	{   tata = x >> 1;
	    if (d[h[tata]] > d[h[x]])
		{   poz[h[tata]] = x;
		    poz[h[x]] = tata;
			h[x] = h[x] + h[tata] - (h[tata] = h[x]);
			x = tata;
		}
		else 
			x = 1;
	}
}
inline int downheap(int x)
{int fiu;
	while (x <= k)
	{   fiu = x;
	    if ((x<<1) <= k)
		{   fiu = x << 1;
			if (fiu + 1 <= k)
				if (d[h[fiu+1]] < d[h[fiu]])
					++fiu;
	    }
		else
			return 0;
	    if (d[h[fiu]] < d[h[x]])
		{   poz[h[fiu]] = x;
		    poz[h[x]] = fiu;
			h[x] = h[x] + h[fiu] - (h[fiu] = h[x]);
			x = fiu;
		}
		else
			return 0;
	}
	return 0;
}
inline void dijkstra()
{int min;
	for (i=2;i<=n;++i)
	{   poz[i] = -1;
	    d[i] = inf;
	} 
	h[1] = poz[1] = 1;
	++k;
	while (k)
	{   min = h[1];
	    h[1] = h[1] + h[k] - (h[k] = h[1]);
		poz[h[1]] = 1;
		--k;
		downheap(1);
		q = v[min];
		while (q)
		{   if (d[q->val] > d[min] + q->cost)
		    {   d[q->val] = d[min] + q->cost;
		        if (poz[q->val] != -1)
					upheap(poz[q->val]);
				else
				{   h[++k] = q -> val;
				    poz[h[k]] = k;
					upheap(k);
				}
			}
			q = q -> next;
		}
	}
}
int main()
{   fscanf(fin,"%d %d",&n,&m);
    for (i=1;i<=m;++i)
	{   fscanf(fin,"%d %d %d",&a,&b,&cost);
		q = new nod;
	    q -> next = v[a];
		q -> val = b;
		q -> cost = cost;
		v[a] = q;
	}
	dijkstra();
	for (i=2;i<=n;++i)
		if (d[i] == inf)
			fout << "0 ";
		else
			fout << d[i] << " ";
	return 0;
}