Pagini recente » Cod sursa (job #1663408) | Cod sursa (job #2716558) | Cod sursa (job #649585) | Cod sursa (job #247209) | Cod sursa (job #3030559)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, x, y, c, i, j, cost[50001], ciclu[50001];
vector <vector <pair <int, int> > > g;
bool bf (int s)
{
queue <int> q;
q.push(s);
while (!q.empty())
{
s = q.front();
q.pop();
ciclu[s]++;
if (ciclu[s] > n) return 0;
for (auto it : g[s])
{
if (cost[it.first] > cost[s]+it.second)
{
cost[it.first] = cost[s]+it.second;
q.push(it.first);
}
}
}
return 1;
}
const int oo = 1e9;
int main()
{
fin >> n >> m; g.resize(n+1);
for (i = 1; i <= m; i++)
{
fin >> x >> y >> c;
g[x].push_back({y, c});
}
for (i = 2; i <= n; i++)
cost[i] = oo;
if (bf(1))
{
for (i = 2; i <= n; i++)
fout << cost[i] << ' ';
}
else fout << "Ciclu negativ!";
return 0;
}