Cod sursa(job #2549465)

Utilizator PandaChanTrusca Daria PandaChan Data 17 februarie 2020 18:33:52
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <vector>
#include <queue>
#define inf 0x3f3f3f3f

using namespace std;

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

struct nod
{
    int vecin, cost;
};

int n, m, viz[105], d[105];
vector <nod> gr[105];
queue <int> q;

void bellman()
{
    while(!q.empty())
    {
        int vf=q.front();
        viz[vf]=0;
        q.pop();
        for(const auto &v:gr[vf])
        {
            int nc=d[vf]+v.cost;
            if(d[v.vecin]>nc)
            {
                d[v.vecin]=nc;
                if(viz[v.vecin]==0)
                {
                    q.push(v.vecin);
                    viz[v.vecin]=1;
                }
            }
        }
    }
}

int main()
{
    f>>n>>m;
    for(int i=1; i<=m; i++)
    {
        int x, y, c;
        f>>x>>y>>c;
        gr[x].push_back({y, c});
    }
    for(int i=2; i<=n; i++)
        d[i]=inf;
    d[1]=0;
    q.push(1);
    viz[1]=1;
    bellman();
    for(int i=1; i<=n; i++)
        g<<d[i]<<" ";

    return 0;
}