Cod sursa(job #2424834)

Utilizator IulianaRusuIuliana Rusu IulianaRusu Data 23 mai 2019 21:49:38
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include<iostream>
#include<fstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define max 10001
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair<int, int> > graph[50050];
queue<int> coada;
int N, M, x, y, c, freq[50001], cost[50001];
int bellmanford()
{
	for (int i = 2; i <= N; i++)
		cost[i] = max;
	cost[1] = 0;
	coada.push(1);
	while (!coada.empty())
	{
		int var = coada.front();
		freq[var]++;
		if (freq[var] >= M)
		{
			fout << "Ciclu negativ!"<<endl;
			return 0;
		}
		coada.pop();
		for (unsigned int i = 0; i < graph[var].size(); i++)
		{
			pair<int, int> x = graph[var][i];
			if (cost[x.first] > cost[var] + x.second)
			{
				cost[x.first] = cost[var] + x.second;
				coada.push(x.first);
			}
		}
	}
	return 1;
}
int main()
{
	fin >> N >> M;
	for (int i = 0; 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;
}