Cod sursa(job #3224605)

Utilizator leelcheeseCiovnicu Denis leelcheese Data 15 aprilie 2024 18:24:31
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>
#include <unordered_map>
#define nmax 100006
#define MOD 9901
#define INF 2012345678
#define ll long long
using namespace std;
//#define fin cin
//#define fout cout

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

int n, m;
vector <pair <int, int>> L[nmax];
queue <int> q;
int cnt[nmax], viz[nmax], d[nmax];

bool BellmanFord(int k)
{
	int i, cost;
	for (i = 1; i <= n; i++)
		d[i] = INF;

	d[k] = 0;
	viz[k] = 1;
	cnt[k]++;
	q.push(k);
	while (!q.empty())
	{
		k = q.front();
		q.pop();
		viz[k] = 0;
		for (auto w : L[k])
		{
			i = w.second;
			cost = w.first;
			if (d[i] > d[k] + cost)
			{
				d[i] = d[k] + cost;
				if (viz[i] == 0)
				{
					viz[i] = 1;
					q.push(i);
					cnt[i]++;
					if (cnt[i] > n)
						return 1;
				}
			}
		}
	}

	return 0;
}

int main()
{
	int i, x, y, c;
	fin >> n >> m;
	for (i = 1; i <= m; i++)
	{
		fin >> x >> y >> c;
		L[x].push_back({ c, y });
	}

	if (BellmanFord(1))
	{
		fout << "Ciclu negativ!\n";
		return 0;
	}

	for (i = 2; i <= n; i++)
		fout << d[i] << " ";
	fout << "\n";

	fout.close();
	fin.close();
	return 0;
}