Pagini recente » Monitorul de evaluare | Cod sursa (job #2358787) | Cod sursa (job #1508137) | Cod sursa (job #2114060) | Cod sursa (job #3342416)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int NMAX = 50000;
int n, x, y, cost, m;
int dist[NMAX+1];
vector < pair<int,int> > v[NMAX+1];
int inq[NMAX+1];
int viz[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));
}
dist[1] = 0;
for(int i=2; i<=n; i++)
dist[i] = INT_MAX;
queue <int> q;
q.push(1);
inq[1] = 1;
viz[1] = 1;
while(!q.empty())
{
int nod = q.front();
viz[nod] = 0;
q.pop();
for(auto a : v[nod])
{
if(dist[a.first] > dist[nod] + a.second)
{
dist[a.first] = dist[nod] + a.second;
if(viz[a.first] == 0)
{
inq[a.first]++;
if(inq[a.first] > n){fout << "Ciclu negativ!";return 0;}
viz[nod] = 1;
q.push(a.first);
}
}
}
}
for(int i=2; i<=n; i++)
fout << dist[i] << ' ';
return 0;
}