Pagini recente » Cod sursa (job #1780332) | Cod sursa (job #2525348) | Cod sursa (job #243255) | Cod sursa (job #1726609) | Cod sursa (job #3280235)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const long long INF = (1LL << 60);
vector< pair < int, int > > G[50001];
queue<int> q;
int cnt[50001], n;
long long cost[50001];
bool neg = false;
void bellmanford()
{
for(int i = 1; i <= n; i++)
{
cost[i] = INF;
}
cost[1] = 0;
q.push(1);
while(!q.empty())
{
int node = q.front();
q.pop();
for(auto it : G[node])
{
int nn = it.first;
int nd = it.second;
if(cost[node] + nd < cost[nn])
{
cost[nn] = cost[node] + nd;
cnt[nn]++;
q.push(nn);
if(cnt[nn] > n)
{
out << "Ciclu negativ!";
neg = true;
while(!q.empty())
{
q.pop();
}
}
}
}
}
}
int main()
{
int m, i, x, y, c;
in >> n >> m;
for(i = 1; i <= m; i++)
{
in >> x >> y >> c;
G[x].push_back({y, c});
}
bellmanford();
if(neg == false)
{
for(i = 2; i <= n; i++)
{
out << cost[i] << " ";
}
}
return 0;
}