Pagini recente » Cod sursa (job #1234211) | Cod sursa (job #2076565) | Cod sursa (job #1340725) | Cod sursa (job #1648158) | Cod sursa (job #2709941)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define INF 0x3f3f3f3f
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair <int , int > > graph[50005];
int n,m,x,y,c;
int viz[50005],d[50005];
bool inq[50005];
queue < int > q;
bool bellmanford(int st)
{
for(int i = 1; i <=n ;i++)
d[i] = INF;
d[st] = 0;
q.push(st);
inq[st] = 1;
while(!q.empty())
{
int vf = q.front();
q.pop();
viz[vf]++;
if(viz[vf] >= n)
return false;
viz[vf] = 0;
for(auto &v : graph[vf])
{
int nod = v.first;
int cost = v.second;
if(d[vf] + cost < d[nod])
{
d[nod] = d[vf] + cost;
if(!inq[nod])
q.push(nod);
}
}
}
return true;
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; i++)
{
fin >> x >> y >> c;
graph[x].push_back({y,c});
}
if(bellmanford(1))
for(int i = 2; i <= n; i++)
fout << d[i] << " ";
else
fout << "Ciclu negativ!";
return 0;
}