Cod sursa(job #1894371)

Utilizator gabrielamoldovanMoldovan Gabriela gabrielamoldovan Data 26 februarie 2017 19:40:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define nmax 50005
#define inf 1e9

using namespace std;

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

vector < vector < pair <int, int> > > a(nmax);
queue <int> Q;
int ap[nmax], dist[nmax];
int n, m;

void citire()
{
    f>>n>>m;
    int x, y, z;
    for(int i=1; i<=m; ++i)
    {
        f>>x>>y>>z;
        a[x].push_back(make_pair(y, z));
    }
}

void init()
{
    dist[1]=0;
    for(int i=2; i<=n; ++i)
    {
        dist[i]=inf;
    }
}

void bellman_ford()
{
    Q.push(1);
    while(Q.size())
    {
        int nod=Q.front();
        Q.pop();
        ap[nod]++;
        if(ap[nod]>m)
        {
            g<<"Ciclu negativ!";
            return ;
        }
        for(int i=0; i<a[nod].size(); ++i)
        {
            int sum=dist[nod]+a[nod][i].second;
            if(sum<dist[a[nod][i].first])
            {
                dist[a[nod][i].first]=sum;
                Q.push(a[nod][i].first);
            }
        }
    }
    for(int i=2; i<=n; ++i)
    {
        g<<dist[i]<<" ";
    }
}

int main()
{
    citire();
    init();
    bellman_ford();
    return 0;
}