Cod sursa(job #1396350)

Utilizator howsiweiHow Si Wei howsiwei Data 22 martie 2015 14:11:05
Problema Algoritmul Bellman-Ford Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

const int oo = 1<<29;

int main() {
	ios::sync_with_stdio(false);
	freopen("bellmanford.in", "r", stdin);
	freopen("bellmanford.out", "w", stdout);
	int n, m;
	cin >> n >> m;
	vector<vector<pair<int,int>>> adjl(n);
	for (int i = 0; i < m; i++) {
		int u, v, w;
		cin >> u >> v >> w;
		u--, v--;
		adjl[u].emplace_back(w, v);
	}

	vector<int> dist(n, oo);
	dist[0] = 0;
	queue<int> q;
	q.push(0);
	vector<bool> inq(n);
	vector<int> l(n);
	vector<int> par(n);

	do {
		int u = q.front();
		q.pop();
		inq[u] = false;
		if (inq[par[u]]) {
			continue;
		}
		for(auto e: adjl[u]) {
			int v = e.second;
			int w = e.first;
			if (dist[v] > dist[u]+w) {
				dist[v] = dist[u]+w;
				if (!inq[v]) {
					l[v] = l[u]+1;
					if (v == 0 || l[v] == n) {
						puts("Ciclu negativ!");
						return 0;
					}
					q.push(v);
					inq[v] = true;
					par[v] = u;
				}
			}
		}
	} while (!q.empty());

	for (int i = 1; i < n; i++) {
		printf("%d%s", dist[i], i < n-1 ? " " : "\n");
	}
	return 0;
}