Pagini recente » Cod sursa (job #1652394) | Cod sursa (job #1833827) | Cod sursa (job #2538892) | Cod sursa (job #636285) | Cod sursa (job #2840235)
#include <bits/stdc++.h>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int nmax = 50005;
const int inf = 2e9;
int n, m, x, y, z, d[nmax], viz[nmax], e;
vector <pair <int, int> > g[nmax];
queue <int> q;
bool inQueue[nmax];
bool bellmanford(int s)
{
for(int i = 1; i <= n; i++ )
d[i] = inf;
d[s] = 0;
q.push(s);
inQueue[s] = true;
while(!q.empty())
{
e = q.front();
q.pop();
viz[e] ++;
inQueue[e] = false;
if(viz[e] >= n)
return false;
for(auto next: g[e])
{
if(d[next.first] > d[e] + next.second)
{
d[next.first] = d[e] + next.second;
if(inQueue[next.first] == false)
{
q.push(next.first);
inQueue[next.first] = true;
}
}
}
}
return true;
}
int main()
{
in >> n >> m;
for(int i = 1; i <= m; i ++)
{
in >> x >> y >> z;
g[x].push_back({y,z});
}
in.close();
if(bellmanford(1))
{
for(int i = 2; i <= n; i ++)
out << d[i] << " ";
}
else
out << "Ciclu negativ!";
out.close();
return 0;
}