Pagini recente » Cod sursa (job #1668963) | Cod sursa (job #2693774) | Cod sursa (job #1628014) | Cod sursa (job #2545847) | Cod sursa (job #2693560)
#include <bits/stdc++.h>
#define MAX 50550
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
struct Edge
{
int destination, weight;
};
vector<Edge> Graph[MAX];
int visited[MAX];
void bellmanford(int startNode)
{
queue<int> q;
vector<int> distance(n + 1, INT_MAX);
q.push(startNode);
distance[startNode] = 0;
while (!q.empty())
{
int current = q.front();
q.pop();
for (auto edge : Graph[current])
{
if (distance[edge.destination] > distance[current] + edge.weight)
{
distance[edge.destination] = distance[current] + edge.weight;
q.push(edge.destination);
visited[edge.destination]++;
if (visited[edge.destination] >= n)
{
fout << "Ciclu negativ!";
return;
}
}
}
}
for (int i = 2; i <= n; i++)
{
fout << distance[i] << " ";
}
}
int main()
{
fin >> n >> m;
for (int i = 0; i < m; i++)
{
int source, destination, weight;
fin >> source >> destination >> weight;
Graph[source].push_back({destination, weight});
}
bellmanford(1);
return 0;
}