Cod sursa(job #2368075)

Utilizator valorosu_300Cristian Gherman valorosu_300 Data 5 martie 2019 13:40:04
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

const int MAX_SIZE = 50002;
const int MAX_VALUE = 1999999999;
struct edge{
    int dest;
    int cost;
};

int d[MAX_SIZE], apare[MAX_SIZE];
bool inQueue[MAX_SIZE];
vector < edge > v[MAX_SIZE];
queue <int> q;

void insertQueue(int val){
    q.push(val);
    inQueue[val] = true;
    apare[val] ++;
}

bool bellman(int n){
    int nbr, sz, c, node;

    for(int i=2;i<=n;i++)
        d[i] = MAX_VALUE;
    d[1] = 0;

    insertQueue(1);
    while(!q.empty()){
        node = q.front();
        q.pop();
        inQueue[node] = false;
        sz = v[node].size();

        for(int i=0;i<sz;i++){
            nbr = v[node][i].dest;
            c = v[node][i].cost;

            if(d[nbr] > d[node] + c){
                d[nbr] = d[node] + c;

                if(inQueue[nbr] == false){
                    if(apare[nbr] >= n - 1)
                        return false;
                    insertQueue(nbr);
                }
            }
        }
    }

    return true;
}

int main()
{
    int n, m, z, y, x;

    in>>n>>m;
    for(int i=1;i<=m;i++){
        in>>x>>y>>z;
        v[x].push_back({y,z});
    }
    in.close();

    if(!bellman(n))
        out<<"Ciclu negativ!";
    else
        for(int i=2;i<=n;i++)
            out<<d[i]<<" ";
    out<<"\n";
    out.close();
    return 0;
}