Cod sursa(job #2628760)

Utilizator dimi999Dimitriu Andrei dimi999 Data 17 iunie 2020 13:17:56
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m;

struct elem
{
    int node, cost;
};

vector <elem> v[50005];

queue <int> q;

int dist[50005];
bool viz[50005];
int ap[50005];


int main()
{
    fin >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        int x, y, z;

        fin >> x >> y >> z;

        v[x].push_back({y,z});
    }

    for(int i = 2; i <= n; i++)
        dist[i] = INT_MAX;

    q.push(1);

    dist[1] = 0;

    viz[1] = 1;

    ap[1] = 1;

    while(!q.empty())
    {
        int Nod = q.front();

        q.pop();

        viz[Nod] = 0;

        for(int i = 0; i < v[Nod].size(); i++)
            if(dist[v[Nod][i].node] > dist[Nod] + v[Nod][i].cost)
        {
            dist[v[Nod][i].node] = dist[Nod] + v[Nod][i].cost;

            ap[v[Nod][i].node]++;

            if(ap[v[Nod][i].node] > n)
                {
                    fout << "Ciclu negativ";
                    return 0;
                }

            if(viz[v[Nod][i].node] == 0)
            {
                viz[v[Nod][i].node] = 1;
                q.push(v[Nod][i].node);
            }
        }
    }

    for(int i = 2; i <= n; i++)
        fout << dist[i] << " ";
    return 0;
}