Cod sursa(job #3198994)

Utilizator andreea.rosuAndreea Rosu andreea.rosu Data 31 ianuarie 2024 12:00:13
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50002
#define INF 26000000

using namespace std;

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

struct arc{int vf, c;};

vector <arc> g[NMAX];
int n, m, start = 1;
int cmin[NMAX], nr[NMAX];
bool circuitneg = 0;
queue <int> C;

int main()
{
    int i, x, y, cost;
    arc a;

    fin >> n >> m;

    for (i = 0; i < m; i++){
        fin >> x >> y >> cost;
        a.vf = y;
        a.c = cost;
        g[x].push_back(a);
    }

    for (i = 1; i <= n; i++)
        cmin[i] = INF;
    cmin[start] = 0;
    C.push(start);
    while (!C.empty() && !circuitneg){
        x = C.front();
        C.pop();

        for (i = 0; i < g[x].size(); i++){
            y = g[x][i].vf;
            cost =  g[x][i].c;
            if (cmin[y] > cmin[x] + cost){
                cmin[y] = cmin[x] + cost;
                nr[y] ++;
                if (nr[y] == n)
                    circuitneg = 1;
                else C.push(y);
            }
        }
    }

    if (circuitneg)
        fout << "Ciclu negativ!";
    else{
        for (i = 2; i <= n; i++)
            fout << cmin[i] << ' ';
    }

    return 0;
}