Cod sursa(job #3260508)

Utilizator TonyyAntonie Danoiu Tonyy Data 2 decembrie 2024 17:00:35
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m;
const int Max = 5e4 + 1;
vector<pair<int,int>> graph[Max];
vector<int> d(Max, INT_MAX), c(Max);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;

void bellman_ford(int node)
{
    q.push({0, node});
    d[node] = 0;
    while(!q.empty())
    {
        node = q.top().second;
        q.pop();
        for(auto const& i: graph[node])
        {
            int neighbour = i.first;
            int cost = i.second;
            if(d[node] + cost < d[neighbour])
            {
                d[neighbour] = d[node] + cost;
                q.push({d[neighbour], neighbour});
                if(++c[neighbour] == n)
                {
                    fout << "Ciclu negativ!";
                    return;
                }
            }
        }
    }
    for(int i = 2; i <= n; ++i)
    {
        fout << d[i] << " ";
    }
}

int main()
{
    ios::sync_with_stdio(false);
    fin.tie(NULL);
    
    int x, y, z;
    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> z;
        graph[x].push_back({y, z});
    }
    bellman_ford(1);

    fin.close();
    fout.close();
    return 0;
}