Pagini recente » Cod sursa (job #2119942) | Cod sursa (job #1376271)
#include <fstream>
#include <queue>
#define N 50001
#define M 250001
#define INF 2147483647
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n, m;
int d[N], it[N];
int lst[N], vf[M], urm[M], cost[M], nvf = 0;
queue<int> q;
bool ok[N];
bool ciclu = 0;
void bellmanford(int x)
{
for(int i = 1; i <= n; i++)
d[i] = INF;
d[x] = 0;
q.push(x);
ok[x] = 1;
while(!q.empty())
{
x = q.front();
q.pop();
ok[x] = 0;
for(int i = lst[x]; i; i = urm[i])
{
int y = vf[i];
int c = cost[i];
if(d[x] + c < d[y])
{
d[y] = d[x] + c;
if(!ok[y])
{
q.push(y);
ok[y] = 1;
if(++it[y] > n)
{
out << "Ciclu negativ!\n";
ciclu = 1;
return;
}
}
}
}
}
}
int main()
{
in >> n >> m;
for(int i = 1; i <= m; i++)
{
int x, y, c;
in >> x >> y >> c;
vf[++nvf] = y;
cost[nvf] = c;
urm[nvf] = lst[x];
lst[x] = nvf;
}
bellmanford(1);
if(ciclu)
return 0;
for(int i = 2; i <= n; i++)
out << d[i] << ' ';
out << '\n';
return 0;
}