Cod sursa(job #2712207)

Utilizator MagnvsDaniel Constantin Anghel Magnvs Data 25 februarie 2021 13:32:15
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int inf = (1<<30)-1;
const int nmax = 50000;

struct str{
    int x, y;
};

vector <str> g[nmax+1];

queue <int> q;
bool inq[nmax+1];
int d[nmax+1], f[nmax+1];

void q_push( int x ) {
    q.push(x);
    inq[x] = 1;
    ++ f[x];
}

int main( ) {
    int n, m;
    fin >> n >> m;
    for ( int i = 1; i <= m; ++ i ) {
        int x, y, z;
        fin >> x >> y >> z;
        str aux;
        aux.x = y;
        aux.y = z;
        g[x].push_back(aux);
    }

    for ( int i = 2; i <= n; ++ i ) {
        d[i] = inf;
    }
    q_push(1);
    bool ok = 1;
    while ( ok == 1 && q.empty() == 0 ) {
        int x = q.front();
        q.pop();
        inq[x] = 0;

        for ( int i = 0; i < int(g[x].size()); ++ i ) {
            int xn = g[x][i].x;
            if ( d[xn] > d[x]+g[x][i].y ) {
                d[xn] = d[x]+g[x][i].y;
                if ( inq[xn] == 0 ) {
                    q_push(xn);
                    if ( f[xn] >= n ) {
                        ok = 0;
                    }
                }
            }
        }
    }

    if ( ok == 1 ) {
        for ( int i = 2; i <= n; ++ i ) {
            fout << d[i] << " ";
        }
        fout << "\n";
    } else {
        fout << "Ciclu negativ!\n";
    }

    return 0;
}