Cod sursa(job #2424010)

Utilizator GashparzPredescu Eduard-Alexandru Gashparz Data 22 mai 2019 14:09:10
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>

using namespace std;

#define  max_size 9999999

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<pair<int, int>> graph[5000001];
queue<int> q;
int cost[5000001];
int freq[5000001];
int N, M, x, y, c;
int bellmanford()
{
	for (int i = 2; i <= N; i++)
		cost[i] = max_size;
	cost[1] = 0;
	q.push(1);
	while (!q.empty())
	{
		int aux = q.front();
		freq[aux]++;
		if (freq[aux] >= M)
		{
			fout << "Ciclu negativ!";
			return 0;
		}
		q.pop();
		for (unsigned int i = 0; i < graph[aux].size(); i++)
		{
			pair<int, int>x = graph[aux][i];
			if (cost[x.first] > cost[aux] + x.second);
			q.push(x.first);
		}
	}
	return 1;
}
int main()
{
	fin >> N >> M;
	for (int i = 1; i <= M; i++)
	{
		fin >> x >> y >> c;
		graph[x].push_back(make_pair(y, c));
	}
	if (bellmanford() == 1)
		for (int i = 2; i <= N; i++)
			fout << cost[i] << " ";
	return 0;
}