Cod sursa(job #3212924)

Utilizator leelcheeseCiovnicu Denis leelcheese Data 12 martie 2024 12:04:06
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
#include <unordered_map>
#define nmax 50005
#define MOD 1999999973
#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];
int d[nmax], cnt[nmax];
bitset <nmax> viz;
queue <int> q;

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

int main()
{
	int i, x, y, c;
	bool ok;
	fin >> n >> m;
	for (i = 1; i <= m; i++)
	{
		fin >> x >> y >> c;
		L[x].push_back({ c, y });
	}
	ok = BellmanFord(1);
	if (ok)
		fout << "Ciclu negativ!";
	else
		for (i = 2; i <= n; i++)
			fout << d[i] << " ";
	fout << "\n";
	fin.close();
	fout.close();
	return 0;
}