Cod sursa(job #2569024)

Utilizator sichetpaulSichet Paul sichetpaul Data 4 martie 2020 10:50:33
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>
#define Nmax 50005
using namespace std;

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

int N, M;
vector<pair<int, int> > G[Nmax];
queue<int> Q;
int nr[Nmax], dp[Nmax];
bool in[Nmax];

int main()
{
    f >> N >> M;
    for (int i = 1; i <= M; ++i) {
        int x, y, c;
        f >> x >> y >> c;
        G[x].push_back({y, c});
    }
    for (int i = 2; i <= N; ++i)
        dp[i] = INT_MAX;

    Q.push(1);
    in[1] = 1;
    while (!Q.empty()) {
        int node = Q.front();
        Q.pop();
        in[node] = 0;
        for (auto it: G[node]) {
            int node2 = it.first, dist2 = dp[node] + it.second;
            if (dist2 >= dp[node2]) continue;
            dp[node2] = dist2;
            ++nr[node2];
            if (nr[node2] == N) {
                g << "Ciclu negativ!\n";
                return 0;
            }

            if (!in[node2]) in[node2] = 1, Q.push(node2);
        }
    }

    for (int i = 2; i <= N; ++i)
         g << dp[i] << " ";

    return 0;
}