Pagini recente » Cod sursa (job #1292665) | Cod sursa (job #786845) | Cod sursa (job #3353312) | Cod sursa (job #1306540) | Cod sursa (job #3343017)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int NMAX = 50000;
int n, m;
int x, y, cost;
vector < pair<int,int> > v[NMAX+1];
int dist_min[NMAX+1];
int viz[NMAX+1];
int inq[NMAX+1];
int main()
{
fin >> n >> m;
for(int i=1; i<=m; i++)
{
fin >> x >> y >> cost;
v[x].push_back(make_pair(y, cost));
}
for(int i=1; i<=n; i++)dist_min[i] = INT_MAX;
dist_min[1] = 0;
viz[1] = 1;
inq[1] = 1;
queue <int> q;
q.push(1);
while(!q.empty())
{
int nod = q.front();
viz[nod] = 0;
q.pop();
for(auto a : v[nod])
{
if(dist_min[a.first] > dist_min[nod] + a.second)
{
dist_min[a.first] = dist_min[nod]+a.second;
if(!viz[a.first])
{
q.push(a.first);
viz[a.first] = 1;
inq[a.first]++;
if(inq[a.first] >= n){cout << "Ciclu negativ!"; return 0;}
}
}
}
}
for(int i=2; i<=n; i++)
fout << dist_min[i] << ' ';
return 0;
}