Cod sursa(job #2423803)

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