Cod sursa(job #2453702)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 5 septembrie 2019 12:19:44
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <queue>
#include <vector>
#define inf 1000000000
using namespace std;

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

queue<int> q;
long n, m, cost[50010], times[50010];
vector<pair<int, int> > G[50010];

int main() {
    f >> n >> m;
    for(int i = 1; i <= m; i++) {
        int a, b, c;
        f >> a >> b >> c;
        G[a].push_back({b, c});
    }


    cost[1] = 0;
    for(int i = 2; i <= n; i++)
        cost[i] = inf;

    q.push(1);
    while(!q.empty()) {
        int a = q.front();
        q.pop();
        times[a]++;
        if(times[a] > n) {
            g << "Ciclu negativ!";
            return 0;
        }

        for(int i = 0; i < G[a].size(); i++) {
            int b = G[a][i].first;
            int c = G[a][i].second;
            if(cost[b] > cost[a] + c) {
                cost[b] = cost[a] + c;
                q.push(b);
            }
        }
    }

    for(int i = 2; i <= n; i++)
        g << cost[i] << ' ';
}