Cod sursa(job #2988972)

Utilizator rARES_4Popa Rares rARES_4 Data 5 martie 2023 17:24:08
Problema Algoritmul Bellman-Ford Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g ("bellmanford.out");
vector<pair<int,int>>adiacenta[50001];
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>> >q;
int cnt[50001];
bool viz[50001];
int dist[50001];
int n,m;
void citire()
{
   f >> n >> m;
   for(int i = 1;i<=m;i++)
   {
       int x,y,c;
        f >> x>> y >> c;
        adiacenta[x].push_back({y,c});
   }
}
void init()
{
    for(int i = 1;i<=50001;i++)
        dist[i]=1<<30-1;
}
int main()
{
    init();
    citire();
    q.push({0,1});
    while(!q.empty())
    {
        int curent = q.top().second;
        int cost = q.top().first;
        q.pop();
        if(viz[curent]==1)
            continue;
        viz[curent] = 1;
        cnt[curent]++;
        if(cnt[curent]>n)
        {
            g << "Ciclu negativ!";
            return 0;
        }
        for(auto x:adiacenta[curent])
        {
            if(dist[x.first]>cost+x.second)
            {
                dist[x.first]= cost+x.second;
                q.push({dist[x.first],x.first});
            }
        }
    }
    for(int i=2;i<=n;i++)
        g << dist[i]<< " ";
}