Pagini recente » Cod sursa (job #1344107) | Cod sursa (job #2587145) | Cod sursa (job #2063255) | Cod sursa (job #2951871) | Cod sursa (job #3215819)
#include <bits/stdc++.h>
#define NMAX 50002
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
struct muchie {
int nod, cost;
};
int n, m, dist[NMAX], cnt[NMAX];
vector<muchie> G[NMAX];
bitset<NMAX> viz;
queue<int> q;
int bellmanford(int start)
{
memset(dist, 0x3f, sizeof(dist));
dist[start] = 0;
q.push(start);
viz[start] = true;
while (!q.empty())
{
int nod = q.front();
q.pop();
viz[nod] = false;
for (auto vec : G[nod])
{
if (dist[vec.nod] > dist[nod] + vec.cost)
{
dist[vec.nod] = dist[nod] + vec.cost;
if (!viz[vec.nod])
{
q.push(vec.nod);
viz[vec.nod] = true;
cnt[vec.nod]++;
if (cnt[vec.nod] > n)
return false;
}
}
}
}
return true;
}
int main()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
fin >> x >> y >> c;
G[x].push_back({y, c});
}
bool ok = bellmanford(1);
if (ok)
{
for (int i = 2; i <= n; i++)
fout << dist[i] << " ";
}
else fout << "Ciclu negativ!";
return 0;
}