Cod sursa(job #3282379)

Utilizator uncle_sam_007ioan bulik uncle_sam_007 Data 5 martie 2025 14:13:57
Problema Algoritmul Bellman-Ford Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 50001;
const int INF = 1e9;

struct Muchie{
    int from, to, cost;
};

vector <Muchie> g;

int dist[NMAX];

int n, m;
bool negative_cycle;

void BellmanFord(){
    for(int i = 1; i <= n; ++i){
        dist[i] = INF;
    }
    dist[1] = 0;
    bool updated;
    for(int i = 1; i < n; ++i){
        updated = false;
        for(auto edge:g){
            int u = edge.from;
            int v = edge.to;
            int c = edge.cost;
            if(dist[u] != INF && dist[u] + c < dist[v]){
                dist[v] = dist[u] + c;
                updated = true;
            }
        }
        if(updated == false){
            break;
        }
    }

    for (auto edge:g) {
        int u = edge.from, v = edge.to, c = edge.cost;
        if (dist[u] != INF && dist[u] + c < dist[v]) {
            negative_cycle = true;
            return;
        }
    }
}

void solve(){
    fin >> n >> m;
    for(int i = 1; i <= m; ++i){
        int x, y, c;
        fin >> x >> y >> c;
        Muchie temp;
        temp.from = x;
        temp.to = y;
        temp.cost = c;
        g.push_back(temp);
    }
    BellmanFord();
    if(negative_cycle == true){
        fout << "Ciclu negativ!";
    }
    else{
        for(int i = 2; i <= n; ++i){
            fout << dist[i] << " ";
        }
    }

}

int main()
{
    solve();
    return 0;
}