Cod sursa(job #3237164)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 5 iulie 2024 19:38:53
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>

std :: ifstream in ("bellmanford.in");

std :: ofstream out ("bellmanford.out");

const int NMAX = 5e4 + 5;

const int INF = 2e9;

int n;

int m;

int x;

int y;

int d;

int aux;

bool modif;

int dist[NMAX];

std :: vector <std :: pair <int, std :: pair <int, int>>> v;

int main()
{

    in >> n >> m;

    for(int i = 1; i <= m; i ++)
    {
        in >> x >> y >> d;

        v.push_back(std :: make_pair (d, std :: make_pair(x, y)));
    }

    aux = n - 1;

    for(int i = 1; i <= n; i ++)
    {
        dist[i] = INF;
    }

    dist[1] = 0;

    while(aux --)
    {
        for(auto i : v)
        {
            if(dist[i.second.first] != INF && dist[i.second.first] + i.first < dist[i.second.second])
            {
                dist[i.second.second] = dist[i.second.first] + i.first;
            }
        }
    }

    for(auto i : v)
    {
        if(dist[i.second.first] != INF && dist[i.second.first] + i.first < dist[i.second.second])
        {
            dist[i.second.second] = dist[i.second.first] + i.first;

            modif = true;
        }
    }

    if(modif == true)
    {
        out << "Ciclu negativ!";
    }
    else
    {
        for(int i = 2; i <= n; i ++)
        {
            out << dist[i] << " ";
        }
    }

    return 0;
}