Pagini recente » Cod sursa (job #1213813) | Cod sursa (job #2869107) | Cod sursa (job #1340430) | Cod sursa (job #2148503) | Cod sursa (job #3237166)
#include <bits/stdc++.h>
std :: ifstream in ("bellmanford.in");
std :: ofstream out ("bellmanford.out");
const int NMAX = 5e4 + 5;
const int INF = 2e9;
int n;
int m;
int x;
int y;
int d;
int dist[NMAX];
int cnt[NMAX];
bool inq[NMAX];
std :: vector <std :: pair <int, int>> v[NMAX];
std :: queue <int> q;
int main()
{
in >> n >> m;
for(int i = 1; i <= m; i ++)
{
in >> x >> y >> d;
v[x].push_back(std :: make_pair(y, d));
}
for(int i = 1; i <= n; i ++)
{
dist[i] = INF;
}
dist[1] = 0;
q.push(1);
inq[1] = true;
while(!q.empty())
{
int nod = q.front();
q.pop();
if(cnt[nod] >= n)
{
out << "Ciclu negativ!";
return 0;
}
inq[nod] = false;
for(auto i : v[nod])
{
if(dist[nod] + i.second < dist[i.first])
{
dist[i.first] = dist[nod] + i.second;
cnt[i.first] ++;
if(inq[i.first] == false)
{
inq[i.first] = true;
q.push(i.first);
}
}
}
}
for(int i = 2; i <= n; i ++)
{
out << dist[i] << " ";
}
return 0;
}