Cod sursa(job #2526750)

Utilizator eli_2003Maria-Elisabeta Mihai eli_2003 Data 19 ianuarie 2020 10:14:28
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;

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

vector< pair< int, int> > g[50005];
int dist[50005];
int n, m;
bool ciclu;
int cnt[500005];
queue<int> q;


void citire() {
    fin >> n >> m;
    int a, b, c;
    for(int i = 1; i <= m; i++) {
        fin >> a >> b >> c;
        g[a].push_back({b, c});
    }
}



void solve() {
    q.push(1);
    for(int i = 1; i <= n; i++)
        dist[i] = 100000000;
    dist[1] = 0;

    while(!q.empty() && !ciclu) {
        int curr = q.front();
        q.pop();
        cnt[curr]++;
        if(cnt[curr] > n) {
            ciclu = true;
            return;
        }

        for(int i = 0; i < g[curr].size(); i++) {
            int next = g[curr][i].first, c = g[curr][i].second;
            if(dist[curr]+c < dist[next]) {
                dist[next] = dist[curr]+c;
                q.push(next);
            }
        }
    }
}

void afis() {
    if(ciclu)
        fout << "Ciclu negativ!";
    else
        for(int i = 2; i <= n; i++)
            fout << dist[i] << ' ';
}

int main() {
    citire();
    solve();
    afis();
}