Pagini recente » Cod sursa (job #1524563) | Cod sursa (job #2206965) | Cod sursa (job #867817) | Cod sursa (job #1387567) | Cod sursa (job #1821468)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int inf = 1000000000, Max = 50010;
struct edge
{
int nod, z;
};
vector<edge> v[Max];
queue<int> q;
int d[Max], sayi[Max], n;
char girmis[Max];
int bellmanFord(int nod)
{
for(int i = 1; i <= n; ++i)
d[i] = inf;
d[nod] = 0;
q.push(nod);
girmis[nod] = 1;
while(!q.empty())
{
int nod = q.front();
q.pop();
girmis[nod] = 0;
for(vector<edge> :: iterator it = v[nod].begin(); it != v[nod].end(); ++it)
{
if(d[it -> nod] > d[nod] + it -> z)
{
d[it -> nod] = d[nod] + it -> z;
if(!girmis[it -> nod])
{
if(++sayi[it -> nod] == n)
return 0;
q.push(it -> nod);
girmis[it -> nod] = 1;
}
}
}
}
return 1;
}
int main()
{
int m, x, y, z;
in >> n >> m;
for(int i = 1; i <= m; ++i)
{
in >> x >> y >> z;
v[x].push_back({y, z});
}
if(!bellmanFord(1))
out << "Ciclu negativ!";
else
{
for(int i = 2; i <= n; ++i)
out << d[i] << " ";
}
return 0;
}