Pagini recente » Cod sursa (job #784555) | Cod sursa (job #2088231) | Cod sursa (job #1583041) | Cod sursa (job #2824119) | Cod sursa (job #2400855)
#include <bits/stdc++.h>
#define INF 100000005
using namespace std;
struct muchie
{
int nod;
int cost;
}aux, aux1;
int n, m, i, x, y, c, nr_distante_pozitive, d[50005];
struct cmp
{
bool operator()(muchie i, muchie j)
{
return i.cost > j.cost;
}
};
priority_queue<muchie, vector<muchie>, cmp> hip;
vector <muchie> v[50005];
int main()
{
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
f >> n >> m;
for(i = 1; i <= m; i ++)
{
f >> x >> y >> c;
aux.nod = y;
aux.cost = c;
v[x].push_back(aux);
}
for(i = 1; i <= n; i ++)
d[i] = INF;
nr_distante_pozitive = n - 1;
d[1] = 0;
aux.nod = 1;
aux.cost = 0;
hip.push(aux);
while(!hip.empty() && nr_distante_pozitive > 0)
{
aux = hip.top();
hip.pop();
if(aux.cost != d[aux.nod])continue;
for(i = 0; i < v[aux.nod].size(); i ++)
{
aux1 = v[aux.nod][i];
if(d[aux1.nod] > d[aux.nod] + aux1.cost)
{
if(d[aux1.nod] >= 0 && d[aux.nod] + aux1.cost < 0)nr_distante_pozitive--;
d[aux1.nod] = d[aux.nod] + aux1.cost;
aux1.cost = d[aux1.nod];
hip.push(aux1);
}
}
}
if(nr_distante_pozitive == 0)g << "Ciclu negativ";
else
{
for(i = 2; i <= n; i ++)
g << d[i] << " ";
}
return 0;
}