Cod sursa(job #2303593)

Utilizator victorv88Veltan Victor victorv88 Data 16 decembrie 2018 16:40:44
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define MAX 1000000000
using namespace std;

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

queue<int>q;
vector<pair<int, int> >graph[50005];

int n, m, from, to, cost, in_queue[50005], numbered[50005], dp[50005];

void solve()
{
    q.push(1);
    in_queue[1]=1;
    numbered[1]=1;
    while (!q.empty())
    {
        int element=q.front();
        q.pop();
        in_queue[element]=0;
        for (auto &v:graph[element])
        {
            if (dp[v.first]>dp[element]+v.second)
            {
                dp[v.first]=dp[element]+v.second;
                if (in_queue[v.first]==0)
                {
                    in_queue[v.first]=1;
                    q.push(v.first);
                    numbered[v.first]++;
                    if (numbered[v.first]>n)
                    {
                        g << "Ciclu negativ!";
                        return;
                    }
                }
            }
        }
    }
    for (int i=2; i<=n; i++)
    {
        g << dp[i] <<' ';
    }
}

int main()
{
    f >> n >> m;
    for (int i=1; i<=m; i++)
    {
        f >> from >> to >> cost;
        graph[from].push_back(make_pair(to,cost));
    }
    for (int i=2; i<=n; i++)
    {
        dp[i]=MAX;
    }
    solve();
    return 0;
}