Cod sursa(job #2920694)

Utilizator andreibrosPeta Andrei Mathias andreibros Data 25 august 2022 13:24:00
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX=50001;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

priority_queue < pair <int,int> > h;
vector <pair <int,int> >graph[NMAX];
int visited[NMAX];
int dist[NMAX];

int main()
{
    int n,m,x,y,cost;
    in>>n>>m;

    for(int i=1; i<=m; i++)
    {
        in>>x>>y>>cost;
        graph[x].push_back(make_pair(y,cost));
    }
    //initializare
    for(int i=1; i<=n; i++)
    {
        dist[i]=INT_MAX;
    }
    dist[1]=0;
    h.push(make_pair(0,1));
    visited[1]++;
    while(h.empty()==false)
    {



        x=h.top().second;
        h.pop();
        for(unsigned int i=0; i<graph[x].size(); i++)
        {
            y=graph[x][i].first;
            cost=graph[x][i].second;
            if(dist[y]>dist[x]+cost)
            {
                dist[y]=dist[x]+cost;
                h.push(make_pair(-dist[y],y));
                visited[y]++;
            }
            if(visited[y]==n)
            {
                out<<"Ciclu negativ!";
                return 0;
            }
        }
    }
    for(int i=2; i<=n; i++)
    {

        out<<dist[i]<<" ";
    }
    return 0;
}