Cod sursa(job #2807527)

Utilizator realmeabefirhuja petru realmeabefir Data 23 noiembrie 2021 21:31:29
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

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

const int INF = 1e9;

vector<pair<int,int>> la[50005];
int dist[50005];
int viz[50005];
int n,m;

int main()
{
    f >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x,y,d;
        f >> x >> y >> d;
        la[x].push_back({y,d});
    }

    for (int i = 1; i <= n; i++)
        dist[i] = INF;

    int s = 1;
    dist[s] = 0;
    priority_queue <pair<int,int>> pq;
    pq.push({0, s});

    while (pq.size())
    {
        int from = pq.top().second;
        viz[from] ++;
        if (viz[from] >= n)
        {
            g << "Ciclu negativ!";
            return 0;
        }
        pq.pop();

        for (auto& per: la[from])
        {
            int to = per.first;
            int cost = per.second;

            if (dist[to] > dist[from] + cost)
            {
                dist[to] = dist[from] + cost;
                pq.push({-dist[to], to});
            }
        }
    }

    for (int i = 2; i <= n; i++)
    {
        if (INF == dist[i])
            dist[i] = 0;
       g << dist[i] << ' ';
    }

    return 0;
}