Pagini recente » Cod sursa (job #420044) | Cod sursa (job #2024528) | Cod sursa (job #2219440) | Cod sursa (job #2796945) | Cod sursa (job #2400866)
#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, d[50005], used[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;
d[1] = 0;
aux.nod = 1;
aux.cost = 0;
hip.push(aux);
while(!hip.empty())
{
aux = hip.top();
hip.pop();
if(aux.cost != d[aux.nod])continue;
used[aux.nod]++;
if(used[aux.nod] == n + 1)
{
g << "Ciclu negativ!";
return 0;
}
for(i = 0; i < v[aux.nod].size(); i ++)
{
aux1 = v[aux.nod][i];
if(d[aux1.nod] > d[aux.nod] + aux1.cost)
{
d[aux1.nod] = d[aux.nod] + aux1.cost;
aux1.cost = d[aux1.nod];
hip.push(aux1);
}
}
}
for(i = 2; i <= n; i ++)
g << d[i] << " ";
return 0;
}