Cod sursa(job #2683783)

Utilizator razvanradulescuRadulescu Razvan razvanradulescu Data 12 decembrie 2020 09:49:49
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#define INF 0x3F3F3F3F
using namespace std;

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

vector<pair<int, int> > graf[50005];
int n, m;
bool inQ[50005];
int cnt[50005], d[50005];
queue<int> Q;

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

void init()
{
    for(int i = 2; i<=n; i++)
    {
        d[i] = INF;
    }
}

int bellman()
{
    Q.push(1);
    cnt[1] = 1;
    while(!Q.empty())
    {
        int node = Q.front();
        cout<<node<<" ";
        inQ[node] = false;
        Q.pop();
        for(auto &p : graf[node])
        {
            if(d[node] + p.second < d[p.first])
            {
                d[p.first] = d[node] + p.second;
                if(!inQ[p.first])
                {
                    Q.push(p.first);
                    cnt[p.first]++;
                    if(cnt[p.first] >= n)
                    {
                        return 1;
                    }
                    inQ[p.first] = true;
                }
            }
        }
    }
    return 0;
}

int main()
{
    read();
    init();
    if(!bellman())
    {
        for(int i = 2; i<=n; i++)
        {
            g<<d[i]<<" ";
        }
    }
    else
    {
        g<<"Ciclu negativ!";
    }
    return 0;
}