Cod sursa(job #3210682)

Utilizator BoggiGurau Bogdan Boggi Data 7 martie 2024 08:36:34
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

const int INF = 0x3f3f3f3f;
struct arc
{
    int x, y, c;/* data */
};

#define VA vector<arc>
#define VI vector<int>
#define pb push_back

int n, m;
VA arce;
VI costMin;

int main() {
    fin >> n >> m;
    costMin = VI(n + 1, INF);
    for (int i = 0; i < m; ++i) {
        arc edge;
        fin >>edge.x >> edge.y >> edge.c;
        arce.pb(edge);
    }
    costMin[1] = 0;
    for (int i = 1; i < n; ++i) {
        for (auto edge : arce) {    
            if (costMin[edge.x] + edge.c < costMin[edge.y]) {
                costMin[edge.y] = costMin[edge.x] + edge.c;
            }
        }
    }
    bool detCircuitNeg = false;
    for (auto edge : arce) {
        if (costMin[edge.x] + edge.c < costMin[edge.y]) {
            detCircuitNeg = true;
            costMin[edge.y] = costMin[edge.x] + edge.c;
        }
    }
    if (detCircuitNeg) {
        fout << "Ciclu negativ!";
    } else {
        for (int nod = 2; nod <= n; ++nod) {
            fout << costMin[nod] << ' ';
        }
    }
}
/*
Avem graful ca lista de muchii
    Bellman-Ford foloseşte fiecare muchie de N-1 ori, repetarea asigurând propagarea distanţei minime prin graf.
     Algoritmul permite detectarea ciclurilor de cost negativ, apărând în cazul în care, după cele N-1 repetiţii,
     există o muchie care îmbunătăţeşte costul vreunui nod. O demonstraţie a algoritmului există pe Wikipedia

CostMin
1    2      3       4     5
0    -5    -3       4     7
Am inteles ca trebuie sa parcurg muchiile de n-1 ori si sa updatez in cazul in care costMin[x] + costArc < costMin[y]
Daca dupa cele n-1 parcurgeri se mai poate imbunatatii un drum inseamna ca avem circuit negativ

*/