Cod sursa(job #3226356)

Utilizator CobzaruAntonioCobzaru Paul-Antonio CobzaruAntonio Data 21 aprilie 2024 10:51:48
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <queue>
using namespace std;
ifstream cin ("bellmanford.in");
ofstream cout ("bellmanford.out");
struct chestie
{
    int nod;
    int d;
};
class Comparare
{
public:
    bool operator() (chestie a,chestie b)
    {
        return a.d > b.d;
    }
};
priority_queue<chestie,vector<chestie>,Comparare> pq;
int dist[50005];
int u[50005];
vector < pair<int,int> > g[50005];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n,m;
    cin >> n >> m;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        cin >> x >> y >> c;
        g[x].push_back({y,c});
    }
    chestie vf,aux;
    for(int i=1;i<=n;i++)
        dist[i] = 2e9;
    dist[1] = 0;
    aux.d = 0;
    aux.nod = 1;
    pq.push(aux);
    while(!pq.empty())
    {
        vf = pq.top();
        pq.pop();
        for(auto much:g[vf.nod])
        {
            if(dist[much.first] <= much.second + vf.d)
                continue;
            dist[much.first] = much.second + vf.d;
            u[much.first]++;
            if(u[much.first]>n)
            {
                cout << "Ciclu negativ!";
                return 0;
            }
            aux.d = dist[much.first];
            aux.nod = much.first;
            pq.push(aux);
        }
    }
    for(int i=2;i<=n;i++)
        cout << dist[i] << ' ';
    return 0;
}