Cod sursa(job #3295136)

Utilizator Cristian_5APuscasu Marian Cristian Cristian_5A Data 2 mai 2025 15:31:10
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>

using namespace std;

vector <pair<int,int>> graph[50005];
int distances[50005];
int noOfNodes[50005];
bool IsInQueue[50005];

void bellman(int source, int n)
{
    for(int i=1; i<=n; i++)
    {
        distances[i]=1e9;
    }
    queue <int> q;
    distances[source]=0;
    noOfNodes[source]=1;
    q.push(source);
    IsInQueue[source]=true;

    while(!q.empty())
    {
        int node = q.front();
        q.pop();
        IsInQueue[node]=false;

        if(noOfNodes[node] > n)
        {
            cout<<"Ciclu negativ!";
            exit(0);
        }

        for(auto x : graph[node])
        {
            if(distances[x.first] > distances[node] + x.second)
            {
                distances[x.first] = distances[node] + x.second;
                noOfNodes[x.first] = noOfNodes[node] + 1;
                if(!IsInQueue[x.first])
                {
                    q.push(x.first);
                }
            }
        }
    }
}

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

int main()
{
    int n, m;
    fin>>n>>m;
    for(int i=0; i<m; i++)
    {
        int u, v, w;
        fin>>u>>v>>w;
        graph[u].push_back({v,w});
    }
    int source = 1;
    bellman(source,n);
    for(int i=2; i<=n; i++)
    {
        fout<<distances[i]<<" ";
    }
    return 0;
}