Pagini recente » Monitorul de evaluare | Istoria paginii utilizator/alexandrarus | Salut cf | Istoria paginii utilizator/info_isa_costin | Cod sursa (job #1551182)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define nmax 50005
#define inf (1<<30)
using namespace std;
int n, m;
int x, y, c;
int cost[nmax];
vector < pair<int, int> > G[nmax];
bool ciclu = false;
int viz[nmax];
queue < pair<int, int> > q;
void bellman()
{
q.push(make_pair(1, 0));
viz[1] = 1;
while (!q.empty())
{
int nod = q.front().first;
int costNod = q.front().second;
q.pop();
for (int i = 0; i < G[nod].size(); i++)
{
int vecin = G[nod][i].first;
int costVecin = G[nod][i].second;
viz[vecin]++;
if (viz[vecin] > n)
{
ciclu = true;
return;
}
else if (cost[vecin] > costNod + costVecin)
cost[vecin] = costNod + costVecin,
q.push(make_pair(vecin, cost[vecin]));
}
}
}
int main()
{
ifstream fi("bellmanford.in");
ofstream fo("bellmanford.out");
fi >> n >> m;
for (int i = 1; i <= m; i++)
fi >> x >> y >> c,
G[x].push_back(make_pair(y, c));
for (int i = 2; i <= n; i++)
cost[i] = inf;
cost[1] = 0;
bellman();
if (ciclu)
fo << "Ciclu negativ!" << "\n";
else
for (int i = 2; i <= n; i++)
fo << cost[i] << " ";
fi.close();
fo.close();
return 0;
}