Cod sursa(job #2206897)

Utilizator Burbon13Burbon13 Burbon13 Data 24 mai 2018 10:33:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#define NMAX 50002
#define INF 0x3f3f3f3f

using namespace std;

int n,m;
int dist[NMAX], viz[NMAX];
vector <pair<int,int>> g[NMAX];
queue <int> q;

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

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

bool bellman_ford()
{
    for(int i = 2; i <= n; ++i)
        dist[i] = INF;
    q.push(1);

    while(not q.empty())
    {
        int nod = q.front();
        q.pop();
        viz[nod] ++;
        if(viz[nod] >= n)
            return false;

        for(auto i: g[nod])
            if(dist[i.first] > dist[nod] + i.second)
            {
                dist[i.first] = dist[nod] + i.second;
                q.push(i.first);
            }
    }

    return true;
}

void afis()
{
    for(int i = 2; i <= n; ++i)
        o << dist[i] << ' ';
}

int main()
{
    citire();
    if(bellman_ford())
        afis();
    else
        o << "Ciclu negativ!\n";
    return 0;
}