Cod sursa(job #2425635)

Utilizator justicebringerArghire Gabriel justicebringer Data 24 mai 2019 22:34:56
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>

using namespace std;

struct bell{
    long long plec;
    long long maDuc;
    long long cost;
};

vector <bell> ADJACENT;
vector <long long > DISTANTA(50010);

int main()
{
    ifstream fin("bellmanford.in");
    ofstream fout("bellmanford.out");
    
    int noduri, muchii;
    fin >> noduri >> muchii;

    for(int i = 1; i <= noduri; i++){
        long long x, y, cost;
        fin >> x >> y >> cost;
        
        bell aux;
        aux.plec = x;
        aux.maDuc = y;
        aux.cost = cost;

        ADJACENT.push_back(aux);
    }    

    for(int i = 1; i <= noduri; i++)
        DISTANTA[i] = 1e12;
    
    DISTANTA[1] = 0;
    for(int i = 1; i <= noduri; i++){
        for(auto it: ADJACENT)
            if(DISTANTA[it.plec] + it.cost < DISTANTA[it.maDuc]){
                DISTANTA[it.maDuc] = DISTANTA[it.plec] + it.cost;
            }
    }

    //--------------------------------------

    for(int i = 1; i <= noduri; i++){
        for(auto it: ADJACENT)
            if(DISTANTA[it.plec] + it.cost < DISTANTA[it.maDuc]){
                fout << "Ciclu negativ!";
                return 0;
            }
    }
    
    for(int i = 2; i <= noduri; i++)
        fout << DISTANTA[i] << " ";

    return 0;
}