Pagini recente » Cod sursa (job #2497908) | Cod sursa (job #3214288) | Cod sursa (job #728827) | Cod sursa (job #2797713) | Cod sursa (job #3286973)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int NMAX = 50000 + 1;
const long long INF = (1LL << 60);
vector< pair <int, int> > G[NMAX];
queue<int> q;
long long cost[NMAX];
int vis[NMAX], n;
bool ok = true;
void BellmanFord(int source)
{
cost[source] = 0;
q.push(source);
while(!q.empty())
{
int node = q.front();
q.pop();
for(auto neigh : G[node])
{
int nn = neigh.first;
int nd = neigh.second;
if(cost[node] + nd < cost[nn])
{
cost[nn] = cost[node] + nd;
vis[nn]++;
if(vis[nn] > n)
{
out << "Ciclu negativ!";
ok = false;
return;
}
q.push(nn);
}
}
}
}
int main()
{
int m, x, y, c;
in >> n >> m;
for(int i = 1; i <= m; i++)
{
in >> x >> y >> c;
G[x].push_back({y, c});
}
for(int i = 1; i <= n; i++)
{
cost[i] = INF;
}
BellmanFord(1);
if(ok)
{
for(int i = 2; i <= n; i++)
{
out << cost[i] << " ";
}
}
return 0;
}