Cod sursa(job #1593247)

Utilizator howsiweiHow Si Wei howsiwei Data 8 februarie 2016 14:19:07
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
#include <list>
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);
	inq[0] = true;
	list<pair<int,int>> lst{{0,0},{0,0}};
	vector<list<pair<int,int>>::iterator> pos(n, lst.end());
	pos[0] = lst.begin();
	// int nrelax = 0;
	do {
		auto u = q.front();
		q.pop();
		if (!inq[u]) continue;
		inq[u] = false;
		for (auto e: adjl[u]) {
			int w = e.first;
			int v = e.second;
			if (dist[v] > dist[u]+w) {
				int dif = dist[u]+w-dist[v];
				dist[v] = dist[u]+w;
				if (pos[v] != lst.end()) {
					int lvl = pos[v]->first;
					auto it = lst.erase(pos[v]);
					while (it->first > lvl) {
						int x = it->second;
						if (x == u) {
							puts("Ciclu negativ!");
							return 0;
						}
						inq[x] = false;
						dist[x] += dif+1;
						pos[x] = lst.end();
						it = lst.erase(it);
					}
				}
				pos[v] = lst.emplace(next(pos[u]), pos[u]->first+1, v);
				if (!inq[v]) {
					q.push(v);
					inq[v] = true;
				}
				// nrelax++;
			}
		}
	} while (!q.empty());
	// printf("%d\n", nrelax);
	for (int i = 1; i < n; i++) {
		printf("%d%c", dist[i],  " \n"[i == n-1]);
	}
}