Pagini recente » Cod sursa (job #2351500) | Cod sursa (job #1423687) | Cod sursa (job #443123) | Cod sursa (job #2297101) | Cod sursa (job #3284213)
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
// Structura pentru a reprezenta o muchie în graf
struct Edge {
int u, v, w;
};
// Funcția Bellman-Ford optimizată cu terminare anticipată
// Calculează distanțele minime de la nodul 'start' către toate celelalte noduri.
// Returnează true dacă nu există cicluri negative, altfel false.
bool bellmanFord(int start, int n, const vector<Edge>& edges, vector<int>& dist) {
dist.assign(n + 1, INF);
dist[start] = 0;
// Relaxăm muchiile de (n - 1) ori, cu posibilitate de terminare anticipată
for (int i = 1; i < n; i++)
{
bool updated = false;
for (int j = 0; j < edges.size(); j++)
{
int u = edges[j].u;
int v = edges[j].v;
int w = edges[j].w;
if (dist[u] != INF && dist[u] + w < dist[v])
{
dist[v] = dist[u] + w;
updated = true;
}
}
// Dacă în această iterație nu s-a făcut nicio actualizare, oprim algoritmul
if (!updated) break;
}
// Verificăm dacă există cicluri negative
for (int j = 0; j < edges.size(); j++) {
int u = edges[j].u;
int v = edges[j].v;
int w = edges[j].w;
if (dist[u] != INF && dist[u] + w < dist[v])
return false; // Ciclul negativ a fost detectat
}
return true;
}
int main() {
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, start = 1;
cin >> n >> m;
vector<Edge> edges;
for (int i = 0; i < m; i++) {
int u, v, cost;
cin >> u >> v >> cost;
edges.push_back({u, v, cost});
}
vector<int> dist;
if (bellmanFord(start, n, edges, dist)) {
for (int i = 2; i <= n; i++) {
cout << (dist[i] == INF ? -1 : dist[i]) << " ";
}
} else {
cout << "Ciclu negativ!";
}
return 0;
}