Pagini recente » Cod sursa (job #2078762) | Cod sursa (job #1737546) | Cod sursa (job #657566) | Cod sursa (job #2030894) | Cod sursa (job #2767906)
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define NMAX 50005
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m, nriq[NMAX], dist[NMAX];
vector <pair <int, int>> edges[NMAX];
bitset <NMAX> iq;
queue <int> q;
bool bf()
{
bool negCycle = 0;
for(int i = 1; i <= n; i++)
dist[i] = INF;
q.push(1);
iq[1] = 1;
nriq[1] = 1;
dist[1] = 0;
while(!q.empty())
{
int nod = q.front();
q.pop();
iq[nod] = 0;
for(auto k : edges[nod])
if(dist[k.first] > dist[nod] + k.second)
{
dist[k.first] = dist[nod] + k.second;
if(!iq[k.first])
{
iq[k.first] = 1;
q.push(k.first);
nriq[k.first]++;
if(nriq[k.first] == n)
return 0;
}
}
}
return 1;
}
int main()
{
f >> n >> m;
for(int i = 1; i <= m; i++)
{
int x, y, cost;
f >> x >> y >> cost;
edges[x].push_back(make_pair(y, cost));
}
if(!bf())
{
g << "Ciclu negativ!";
return 0;
}
for(int i = 2; i <= n; i++)
g << dist[i] << " ";
return 0;
}