Cod sursa(job #2864678)

Utilizator MR0L3eXMaracine Constantin Razvan MR0L3eX Data 8 martie 2022 09:07:36
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include "bits/stdc++.h"

using namespace std;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

using ll = long long;
using ull = unsigned long long;

const ll INF = 1e18;

using T = array<ll, 2>;

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

int32_t main() {
    ios::sync_with_stdio(false);
    cin.tie(0);


    int n, m;
    fin >> n >> m;
    vector<vector<T>> adj(n);
    for (int i = 0; i < m; ++i) {
        ll a, b, c;
        fin >> a >> b >> c;
        --a, --b;
        adj[a].push_back({c, b});
    }
    vector<ll> dist(n, INF);
    vector<int> cnt(n);
    dist[0] = 0;

    queue<int> Q;
    Q.push(0);
    while (!Q.empty()) {
        int v = Q.front();
        Q.pop();
        for (T u : adj[v]) {
            if (dist[v] + u[0] < dist[u[1]]) {
                dist[u[1]] = dist[v] + u[0];
                if (cnt[u[1]] > n) {
                    fout << "Ciclu negativ!\n";
                    return 0;
                }
                Q.push(u[1]);
                ++cnt[u[1]];
            }
        }
    }

    for (int i = 1; i < n; ++i) {
        fout << dist[i] << ' ';
    }
    fout << "\n";
}