Pagini recente » Cod sursa (job #1028029) | Cod sursa (job #1790174) | Cod sursa (job #671869) | Cod sursa (job #1340767) | Cod sursa (job #2969633)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int NMAX = 50007;
vector<vector<pair<int, int>>> v(NMAX);
int main()
{
int n, m;
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
fin >> x >> y >> c;
v[x].emplace_back(y, c);
}
vector<int> d(n + 1, INT_MAX);
d[1] = 0;
vector<bool> ok(n + 1, false);
vector<int> inqueue(n + 1, 0);
queue<int> q;
q.push(1);
ok[1] = true;
inqueue[1] = 1;
while (!q.empty())
{
int nod = q.front();
q.pop();
ok[nod] = false;
for (auto i: v[nod])
{
int vecin = i.first;
int cost = i.second;
if (d[vecin] > d[nod] + cost)
{
d[vecin] = d[nod] + cost;
if (!ok[vecin])
{
q.push(vecin);
ok[vecin] = true;
inqueue[vecin]++;
if (inqueue[vecin] > n)
{
fout << "Ciclu negativ!";
return 0;
}
}
}
}
}
for(int i = 2; i <= n; i++)
fout << d[i] << " ";
return 0;
}