Pagini recente » Cod sursa (job #1769875) | Cod sursa (job #2387527) | Cod sursa (job #3175680) | Cod sursa (job #372249) | Cod sursa (job #2870129)
#include <bits/stdc++.h>
#define INF 1000000004
#define NMAX 50004
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
int n, m;
int dp[NMAX];
int fr[NMAX];
vector < pair <int, int> > G[NMAX];
queue <int> Q;
void citire();
bool Bellman_Ford(int start);
void afisare();
int main()
{
citire();
afisare();
return 0;
}
void citire()
{
int x, y, c;
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> c;
G[x].push_back({y, c});
}
for (int i = 1; i <= n; i++)
dp[i] = INF;
}
bool Bellman_Ford(int start)
{
Q.push(start);
dp[start] = 0;
fr[start]++;
while (!Q.empty())
{
int nod = Q.front();
Q.pop();
for (int i = 0; i < G[nod].size(); i++)
{
int vf = G[nod][i].first;
int cost = G[nod][i].second;
if (dp[vf] > dp[nod] + cost)
{
dp[vf] = dp[nod] + cost;
fr[vf]++;
Q.push(vf);
if (fr[vf] == n)
return 0;
}
}
}
return 1;
}
void afisare()
{
if (Bellman_Ford(1))
{
for (int i = 2; i <= n; i++)
if (dp[i] == INF)
fout << 0 << ' ';
else
fout << dp[i] << ' ';
}
else
fout << "Ciclu negativ!";
}