Pagini recente » Cod sursa (job #1245398) | Cod sursa (job #2202643) | Cod sursa (job #2626536) | Cod sursa (job #1024664) | Cod sursa (job #3269544)
#include <bits/stdc++.h>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int NMAX = 50000, INF = 1e9;
vector <pair<int, int>> graph[NMAX+1];
vector <int> dist(NMAX+1, INF), cnt(NMAX+1, 0);
bitset <NMAX+1> inq;
int n, m;
bool bellman(int start)
{
queue <int> q;
q.push(start);
inq[start] = 1;
dist[start] = 0;
cnt[start]++;
while(!q.empty())
{
int node = q.front();
q.pop();
inq[node] = 0;
for(auto [next, price]:graph[node])
{
if(inq[next] == 0 && dist[node] + price < dist[next])
{
dist[next] = dist[node] + price;
cnt[next]++;
inq[next] = 1;
q.push(next);
if(cnt[next] >= n)
{
return 1;
}
}
}
}
return 0;
}
int main()
{
int a, b, c;
in>>n>>m;
for(int i=1; i<=m; i++)
{
in>>a>>b>>c;
graph[a].push_back({b, c});
}
bool rez = bellman(1);
if(rez == 1)
{
out<<"Ciclu negativ!";
return 0;
}
for(int i=2; i<=n; i++)
{
out<<dist[i]<<" ";
}
return 0;
}