Pagini recente » Cod sursa (job #2810355) | Cod sursa (job #1684234) | Cod sursa (job #1774390) | Cod sursa (job #616339) | Cod sursa (job #2569151)
#include <fstream>
#include <vector>
#include <queue>
using namespace std ;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int inf = 1e3 + 1;
int n, m;
int main()
{
in >> n >> m;
vector < pair <int, int> > adj[n + 1];
for(int i = 1; i <= m; ++ i)
{
int x, y, cost;
in >> x >> y >> cost;
adj[x].push_back({y, cost});
}
vector <bool> added(n + 1, false);
vector <int> dist(n + 1, inf), visits (n + 1, 0);
queue <int> q;
dist[1] = 0;
q.push(1);
while(!q.empty())
{
int node = q.front();
q.pop();
++ visits[node];
added[node] = false;
if(visits[node] == n)
{
out << "Ciclu negativ!";
return 0;
}
for(auto i : adj[node])
{
int nextnode = i.first, weight = i.second;
if(dist[nextnode] > dist[node] + weight)
{
dist[nextnode] = dist[node] + weight;
if(!added[nextnode])
{
q.push(nextnode);
added[nextnode] = true;
}
}
}
}
for(int i = 2; i <= n; ++ i)
out << dist[i] << ' ';
return 0;
}