Cod sursa(job #348318)

Utilizator ScrazyRobert Szasz Scrazy Data 15 septembrie 2009 12:23:27
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;
const int maxn = 50001;

#define inf 0x3f3f3f3f

vector<pair<int,int> > G[maxn];
int dist[maxn];

int n, m;

struct qitem
{
	int nod, dist;
	qitem() {};
	qitem(int a, int b)
	{
		nod = a; dist = b;
	}
	bool operator <(const qitem &q) const
	{
		return dist > q.dist;
	}
};

void read()
{
	scanf("%d%d", &n, &m);
	for (; m; --m)
	{
		int a, b, c; scanf("%d%d%d", &a, &b, &c);
		G[a].push_back(make_pair(b, c));
	}
}

priority_queue<qitem> Q;

void dijkstra()
{
	memset(dist, 0x3f, sizeof(dist));
	dist[1] = 0;
	Q.push(qitem(1, 0));
	while (!Q.empty())
	{
		int nod = Q.top().nod;
		int d = Q.top().dist;
		Q.pop();
		if (d > dist[nod]) continue;
		for (int i = 0; i < G[nod].size(); ++i)
		{
			int next = G[nod][i].first;
			int edge = G[nod][i].second;

			if (dist[next] > dist[nod] + edge)
			{
				dist[next] = dist[nod] + edge;
				Q.push(qitem(next, dist[next]));
			}
		}
	}
}

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

	read();
	dijkstra();

	for (int i = 2; i <= n; ++i)
		printf(dist[i] == inf ? "0 " : "%d ", dist[i]);

	return 0;
}