Cod sursa(job #1452116)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 19 iunie 2015 21:28:27
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define pll pair<ll, ll>
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second

const int nmax = 50005;
const int inf = 1 << 30;

int n, m, x, y, z;
int d[nmax];

vector<pii> v[nmax];
bitset<nmax> viz;
priority_queue<pii, vector<pii>, greater<pii>> q;

void dijkstra(int source) {
	for (int i = 1; i <= n; i++)
		d[i] = inf;

	d[source] = 0;
	q.push(mp(d[source], source));

	while (!q.empty()) {
		int x = q.top().se;
		q.pop();

		if (viz[x]) continue;
		viz[x] = 1;

		for (auto it : v[x]) {
			int y = it.fi;
			int cost = it.se;
			if (d[x] + cost < d[y]) {
				d[y] = d[x] + cost;
				q.push(mp(d[y], y));
			}
		}
	}
}

int main() {

	fin >> n >> m;

	for (; m; m--) {
		fin >> x >> y >> z;
		v[x].pb(mp(y, z));
	}

	dijkstra(1);

	for (int i = 2; i <= n; i++)
		fout << ((d[i] == inf) ? 0 : d[i]) << " ";

	return 0;
}