Pagini recente » Diferente pentru utilizator/vman intre reviziile 82 si 61 | Monitorul de evaluare | Monitorul de evaluare | Autentificare | Cod sursa (job #2654120)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
int n, m;
bool cycle;
int dist[50005];
int cnt[50005];
bool inq[50005];
const int INF = 100000000;
queue < int > q;
vector < pair < int, int > > v[250005];
void Read ()
{
f >> n >> m;
for (int i=1; i<=m; i++)
{
int x, y, cost;
f >> x >> y >> cost;
v[x].push_back(make_pair(y, cost));
}
for (int i=1; i<=n; i++)
dist[i] = INF;
}
void BellmanFord (int start)
{
inq[start] = 1, dist[start] = 0;
q.push(start);
while (!q.empty() && !cycle)
{
int nod = q.front();
int lg = v[nod].size();
q.pop();
inq[nod] = 0;
for (int i=0; i<lg; i++)
{
int nod_nou = v[nod][i].first;
int cost = v[nod][i].second;
if (dist[nod] + cost < dist[nod_nou])
{
dist[nod_nou] = dist[nod] + cost;
cnt[nod_nou] = cnt[nod] + 1;
if (cnt[nod_nou] > n-1) cycle = true;
if (!inq[nod_nou])
{
q.push(nod_nou);
inq[nod_nou] = 1;
}
}
}
}
}
void Print ()
{
for (int i=2; i<=n; i++)
g << dist[i] << " ";
}
int main()
{
Read();
BellmanFord(1);
if (cycle) g << "Ciclu Negativ!";
else Print();
return 0;
}