Cod sursa(job #2842407)

Utilizator anaop32Oprea Ana-Maria anaop32 Data 31 ianuarie 2022 19:14:13
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>
using namespace std;

int main(){
    ifstream f("bellmanford.in");
    ofstream g("bellmanford.out");

    int n, m, nod1, nod2, cost;

    f >> n >> m;
    //vector<vector<pair<int, int>>> lv;
    vector<vector<int>> muchii;

    for (int i = 0; i < m; i++){
        // vector<pair<int,int>> aux;
        // lv.push_back(aux);
        vector<int> a;
        muchii.push_back(a);
    }
    
    for (int i = 0; i < m; i++){
        f >> nod1;
        f >> nod2;
        f >> cost;
        // lv[nod1 - 1].push_back(make_pair(nod2 -1, cost));
        muchii[i].push_back(nod1 - 1);
        muchii[i].push_back(nod2 - 1);
        muchii[i].push_back(cost);
    }

    vector<int> dist(n, 1e9);
    vector<int> vizitat(n, false);

    dist[0] = 0;

    for (int i = 0; i < n; i ++){
        for (int j = 0; j < m; j++) {
            int sursa = muchii[j][0];
            int destinatie = muchii[j][1];
            cost = muchii[j][2];

            if (dist[sursa] + cost < dist[destinatie])
                dist[destinatie] = cost + dist[sursa];
        }
    }

    for (int j = 0; j < m; j++) {
        int sursa = muchii[j][0];
        int destinatie = muchii[j][1];
        cost = muchii[j][2];

        if (dist[sursa] + cost < dist[destinatie])
            dist[destinatie] = cost + dist[sursa];
    }

    for (int i = 0; i < n; i++){
        cout << dist[i] << " ";
    }

    return 0;
}