Cod sursa(job #2453697)

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

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

queue<int> q;
long n, m, cost[50010], times[50010];
struct muchie{
    long a, b, c;
} muchii[250010];

int main() {
    f >> n >> m;
    for(int i = 1; i <= m; i++)
        f >> muchii[i].a >> muchii[i].b >> muchii[i].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 = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
                if(cost[muchii[j].a] + muchii[j].c < cost[muchii[j].b]) {
                    cost[muchii[j].b] = cost[muchii[j].a] + muchii[j].c;
                    q.push(muchii[j].b);
                }
    }

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