Pagini recente » Cod sursa (job #20946) | Cod sursa (job #2436931) | Cod sursa (job #2072998) | Cod sursa (job #1566327) | Cod sursa (job #2434985)
#include <fstream>
#include <vector>
#include <queue>
#define nmax 50005
#define mmax 250005
#define oo 2000000005
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
vector < pair < int , int > > E[nmax + 5];
vector < int > D(nmax + 5, oo), F(nmax + 5, 0);
queue < int > Q;
int n, m, x, y, cost; bool negativ = false;
void Bell()
{
while (!Q.empty())
{
int node = Q.front();
Q.pop();
for (auto it : E[node])
{
if (D[it.first] > D[node] + it.second)
{
D[it.first] = D[node] + it.second;
F[it.first]++;
Q.push(it.first);
if (F[it.first] == n)
{
negativ = true;
return;
}
}
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
cin >> x >> y >> cost;
E[x].push_back({y, cost});
}
D[1] = 0;
Q.push(1);
Bell();
if (negativ) return cout << "Ciclu negativ!\n", 0;
for (int i = 2; i <= n; i++) cout << D[i] << " ";
return 0;
}