Cod sursa(job #2423812)

Utilizator lulu1602Pantiru Luana Catalina lulu1602 Data 21 mai 2019 22:53:13
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include<iostream>
#include<fstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define inf 999999999
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair<int, int>> graf[50050];
queue<int> q;
int N, M, a, b, c, freq[50050], cost[50050];
int bellmanford()
{
	for (int i = 2; i <= N; i++)
		cost[i] = inf;
	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 < graf[aux].size(); i++)
		{
			pair<int, int> x = graf[aux][i];
			if (cost[x.first] > cost[aux] + x.second)
			{
				cost[x.first] = cost[aux] + x.second;
				q.push(x.first);
			}
		}
	}
	return 1;
}
int main()
{
	fin >> N >> M;
	for (int i = 0; i <M; i++)
	{
		fin >> a >> b >> c;
		graf[a].push_back(make_pair(b, c));
	}
	if(bellmanford()==1)
	for (int i = 2; i <= N; i++)
		fout << cost[i] << " ";
	system("pause");
}