Cod sursa(job #2071557)

Utilizator DenisacheDenis Ehorovici Denisache Data 20 noiembrie 2017 19:40:40
Problema Algoritmul Bellman-Ford Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <bitset>

using namespace std;



int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	ifstream f("bellmanford.in");
	ofstream g("bellmanford.out");

	#define cin f
	#define cout g

	int n, m;
	cin >> n >> m;

	vector< pair<int, int> > *G = new vector< pair<int, int> >[n];

	for (int i = 0; i < m; ++i) {
		int a, b, cost;
		cin >> a >> b >> cost;
		--a; --b;

		G[a].push_back( make_pair(b, cost) );
	}

	const int INF = int(1e9);
	vector<int> dist(n, INF);
	vector<int> cnt(n, 0);
	bitset<50005> in_queue(false);

	int source = 0;
	dist[source] = 0;
	in_queue[source].flip();

	queue<int> nodes;
	
	nodes.push(source);

	while (!nodes.empty()) {
		int node = nodes.front();
		in_queue[node].flip();

		nodes.pop();

		for (pair<int, int> edge: G[node]) {
			if (dist[node] + edge.second < dist[edge.first] && !in_queue[edge.first]) {
				if (cnt[node] == n) {
					cout << "Ciclu negativ!";
					return 0;
				}

				dist[edge.first] = dist[node] + edge.second;
				in_queue[edge.first].flip();
				++cnt[edge.first];
				nodes.push(edge.first);
			}
		}
	}

	for (int i = 1; i < n; ++i)
		cout << dist[i] << " ";

	delete[] G;

	//system("pause");

	return 0;
}