Cod sursa(job #2569020)

Utilizator Anastasia11Susciuc Anastasia Anastasia11 Data 4 martie 2020 10:49:46
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
#define Nmax 50005
#define INF 0x3f3f3f3f

using namespace std;

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

int n, m;
vector <pair <int, int> > v[Nmax];
int d[Nmax], viz[Nmax];
queue <int> Q;

int main()
{
    f >> n >> m;
    for (int i = 1, x, y, c; i <= m; i++)
    {
        f >> x >> y >> c;
        v[x].push_back({y, c});
    }
    for (int i = 1; i <= n; i++) d[i]=INF;
    Q.push(1);
    d[1]=0;
    while (!Q.empty())
    {
        int x=Q.front(); Q.pop();

        for (auto i:v[x])
        {
            int y=i.first, c=i.second;

            if (d[y] > d[x]+c)
            {
                d[y]=d[x]+c;
                Q.push(y);
                viz[y]++;
            }
            if (viz[y] > n)
            {
                g << "Ciclu negativ!";
                return 0;
            }
        }
    }

    for (int i = 2; i <= n; i++)
        g << d[i] << " ";


    return 0;
}