Cod sursa(job #850117)

Utilizator Luncasu_VictorVictor Luncasu Luncasu_Victor Data 7 ianuarie 2013 23:42:03
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <stack>
#include <cassert>
using namespace std;

#define PRO "ciur"
void OpenFiles(int EVAL)
{
	if(EVAL)
	{
		char input[100] = PRO, output[100] = PRO;
		freopen(strcat(input, ".in"),"r",stdin);
		freopen(strcat(output,".out"),"w",stdout);
	} else
	{
		freopen("test.in","r",stdin);
		freopen("test.out","w",stdout);
	}
}

#define MAX 50001
#define INF 0xffffff

vector<pair<int,int> >g[MAX];
struct DHeap{ int x,c; }h[MAX];
int n,k,dist[MAX],pos[MAX];

void Push(int x,int c)
{
	int t,f;
	if(pos[x]==0)
	{
		f=++k;
		h[f].x=x;
		h[f].c=c;
		pos[x]=f;
	} else
	{
		f=pos[x];
		h[f].c=c;
	}
	t=f/2;
	while(t>0 && h[f].c<h[t].c)
	{
		swap(h[t],h[f]);
		swap(pos[h[t].x],pos[h[f].x]);
		f=t; t=f/2;
	}
}

void Pop()
{
	int t,f;
	h[1]=h[k--];
	pos[h[1].x]=1;
	t=1;
	f=2;
	if(f+1<=k && h[f+1].c<h[f].c)f++;
	while(f<=k && h[f].c<h[t].c)
	{
		swap(h[t],h[f]);
		swap(pos[h[t].x],pos[h[f].x]);
		t=f;
		f=2*t;
		if(f+1<=k && h[f+1].c<h[f].c)f++;
	}
}

void Dijkstra()
{
	int x,c;
	for(int i=2;i<=n;i++) dist[i]=INF;
	k=1;
	h[1].x=1;
	h[1].c=0;
	while(k>0)
	{
		x=h[1].x;
		c=h[1].c;
		Pop();
		for(int i=0;i<g[x].size();i++)
			if(dist[g[x][i].first] > c + g[x][i].second)
			{
				dist[g[x][i].first]=c+g[x][i].second;
				Push(g[x][i].first,dist[g[x][i].first]);
			}
	}
}

int main(int argv,char *args[])
{
	OpenFiles(argv==0);	
	// start
	int m,x,y,c;
		scanf("%d %d",&n,&m);
		for(int i=1;i<=m;i++)
		{
			scanf("%d %d %d",&x,&y,&c);
			g[x].push_back(make_pair(y,c));
		}
		Dijkstra();
		for(int i=2;i<=n;i++)printf("%d ",dist[i]==INF?0:dist[i]);
	return 0;
}