Cod sursa(job #2423788)

Utilizator lulu1602Pantiru Luana Catalina lulu1602 Data 21 mai 2019 22:17:47
Problema Algoritmul Bellman-Ford Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
#define inf 100000000;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int N, M;
vector< pair<int,pair <int,int> >>graf;
queue<int>myheap;
int cost[50005],freq;
int bellmanford()
{
	for (int i = 2; i <= N; i++)
		cost[i] = inf;
	cost[1] = 0;
	while (freq <= N - 1)
	{
		freq++;
		int l = graf.size();
		for (int i = 0; i < l; i++)
		{
			int s, f, c;
			s = graf[i].first;
			f = graf[i].second.first;
			c = graf[i].second.second;
			if (cost[f] > cost[s] + c)
				cost[f] = cost[s] + c;
		}
	}
	if (freq > M - 1) return 0;
	return 1;
}
int main()
{
	int x, y, c;
	fin >> N >> M;
	for (int i = 0; i < M; i++)
	{
		fin >> x >> y >> c;
		graf.push_back(make_pair(x,make_pair(y, c)));
	}
	if(bellmanford()==1)
	for (int i = 2; i <= N; i++)
		fout << cost[i] << " ";
	else fout << "Ciclu negativ!";
	system("pause");
}