Pagini recente » Cod sursa (job #2836810) | Borderou de evaluare (job #565570) | Cod sursa (job #2739301) | Cod sursa (job #3278362) | Cod sursa (job #2529000)
#include <bits/stdc++.h>
#define N 50005
#define INF INT_MAX
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
int n, m, cost[N], cntViz[N];
bool inCoada[N], ciclu;
queue <int> Q;
vector < pair <int, int> > L[N];
void Citire()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int a, b, c;
fin >> a >> b >> c;
L[a].push_back(make_pair(b, c));
}
}
void Solve()
{
for (int i = 2; i <= n; i++)
cost[i] = INF;
cntViz[1] = 1;
Q.push(1);
inCoada[1] = 1;
while (!Q.empty() && !ciclu)
{
int nod = Q.front();
Q.pop();
inCoada[nod] = 0;
for (auto i : L[nod])
{
int nextNod = i.first;
int costMuchie = i.second;
if (cost[nextNod] > cost[nod] + costMuchie)
{
cost[nextNod] = cost[nod] + costMuchie;
cntViz[nextNod]++;
if (cntViz[nextNod] == n)
ciclu = 1;
else
{
if (!inCoada[nextNod])
{
Q.push(nextNod);
inCoada[nextNod] = 1;
}
}
}
}
}
if (ciclu)
fout << "Ciclu negativ!";
else
for (int i = 2; i <= n; i++)
fout << cost[i] << " ";
}
int main()
{
Citire();
Solve();
return 0;
}