Cod sursa(job #528447)

Utilizator maooBompa Mario maoo Data 2 februarie 2011 20:50:59
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include<fstream>
#include<cstdio>
#include<vector>
#include<utility>
#define ff it->first
#define ss it->second

using namespace std;
int n,m,a,b,c,d[50005],oo=500000000,h[50010],poz[50010],i,l,nod,dist,bau;
void read(),solve(),hu(int t),hd(int f);
vector <pair<int,int> > v[50010];
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int main()
{
	read();
	solve();
	return 0;
}
void read()
{	
	in>>n>>m;
	for(;m;m--)
	{
		in>>a>>b>>c;
		v[a].push_back(make_pair(b,c));
	}
}
void solve()
{
	vector<pair<int,int> >::iterator it;
	for(i=1;i<=n;i++)
	{
		h[i]=i;
		d[i]=oo;
		poz[i]=i;
	}
	d[1]=0;
	l=n;
	for(;l;)
	{
		nod=h[1];
		dist=d[nod];
		for(it=v[nod].begin();it!=v[nod].end();it++)
			if(d[ff]>dist+ss)
			{
				d[ff]=dist+ss;
				hu(poz[ff]);
			}
		h[1]=h[l];
		poz[h[1]]=1;
		l--;
		hd(1);
	}
	for(i=2;i<=n;i++)
	{
		if(d[i]==oo)
			d[i]=0;
	}
	for(i=2;i<=n;i++)
		out<<d[i]<<" ";
	out<<endl;
}

void hu(int f)
{
	
	int t,aux;
	for(;;)
	{
		t=f>>1;
		if(d[h[t]]<=d[h[f]])
			return;
		aux=h[t];
		h[t]=h[f];
		h[f]=aux;
		poz[h[t]]=t;
		poz[h[f]]=f;
		f=t;
	}
}
void hd(int t)
{
	int f,aux;
	for(;;)
	{
		f=t<<1;
		if(f>l)
			return;
		if(f<l)
			if(d[h[f+1]]<d[h[f]])
				f++;
		if(d[h[t]]<=d[h[f]])
			return;
		aux=h[t];
		h[t]=h[f];
		h[f]=aux;
		poz[h[t]]=t;
		poz[h[f]]=f;
		t=f;
	}
}