Cod sursa(job #3161046)

Utilizator AlexInfoIordachioaiei Alex AlexInfo Data 25 octombrie 2023 16:44:40
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>

using namespace std;

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

typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
#define fi first
#define se second

#define NMAX 50005
#define MOD 1000000007
#define INF 0x3f3f3f3f

vector<vector<pii>> graf(NMAX);
int n, ans, dist[NMAX], cnt[NMAX];

void read()
{
    int x, y, wt, m;
    in >> n >> m;
    while (m--)
        in >> x >> y >> wt, graf[x].emplace_back(y, wt);
}

void BellmanFord(int start)
{
    memset(dist, INF, sizeof dist);

    dist[start] = 0;
    queue<pii> Q;
    Q.push({start, 0});

    while (!Q.empty())
    {
        int u, cost;
        tie(u, cost) = Q.front();
        Q.pop();

        for (auto node : graf[u])
        {
            int to = node.fi, currcost = node.se;
            if (cost + currcost < dist[to])
            {
                dist[to] = cost + currcost, Q.push({to, dist[to]});
                cnt[to]++;
                if (cnt[to] == n + 2)
                {
                    out << "Ciclu negativ!";
                    exit(0);
                }
            }
        }
    }
}

void solve()
{
    BellmanFord(1);
    for (int i = 2; i <= n; i++)
        out << dist[i] << ' ';
}

int main()
{
    read();
    solve();
    return 0;
}