Pagini recente » Cod sursa (job #2084524) | Cod sursa (job #1844165) | Cod sursa (job #2101742) | Cod sursa (job #453233) | Cod sursa (job #3272298)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<int> dist;
bool bellman(vector<vector<pair<int, int>>> &graph, int n, int start)
{
queue<int> q;
vector<bool> visited(n + 1, false);
vector<int> count(n + 1, 0);
dist.resize(n + 1, 1e9);
dist[start] = 0;
q.push(start);
visited[start] = true;
while (!q.empty())
{
int node = q.front();
q.pop();
visited[node] = false;
for (auto [neigh, w]: graph[node])
{
if (dist[node] != 1e9 && dist[node] + w < dist[neigh])
{
dist[neigh] = dist[node] + w;
if (!visited[neigh])
{
q.push(neigh);
visited[neigh] = true;
count[neigh]++;
if (count[neigh] > n)
{
return false;
}
}
}
}
}
for (int i = 2; i <= n; i++)
{
if (dist[i] == 1e9)
{
fout << -1 << ' ';
}
else
{
fout << dist[i] << ' ';
}
}
return true;
}
int main()
{
int n, m;
fin >> n >> m;
vector<vector<pair<int, int>>> graph(n + 1);
for (int i = 1; i <= m; i++)
{
int a, b, c;
fin >> a >> b >> c;
graph[a].emplace_back(b, c);
}
if (!bellman(graph, n, 1))
{
fout << "Ciclu negativ!";
}
return 0;
}