Cod sursa(job #3189202)

Utilizator xxUnrealUxxNiculae Adrian-Ioan xxUnrealUxx Data 4 ianuarie 2024 17:26:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
#include <queue>
#define Nmax 500002
#define Mmax 250002
using namespace std;

ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");

int n, m;
vector<pair<int, int>> mat[Nmax];
queue<int> q;
vector<int> dist(Nmax, 1e9);
int viz[Nmax], cnt[Nmax];


void citire()
{
    cin >> n >> m;

    for(int i = 0, a, b, c; i<m; i++)
    {
        cin >> a >> b >> c;
        mat[a].push_back({b, c});
    }
}

void Bellman_Ford()
{
    for(int i = 1; i<=n; i++)
        dist[i] = 1e9;

    dist[1] = 0;
    q.push(1);
    //viz[1] = 1;

    while(!q.empty())
    {
        int k = q.front();
        q.pop();
        viz[k] = 0;

        for(auto it : mat[k])
        {
            int cost = it.second;
            int dest = it.first;

            if(dist[k] + cost < dist[dest])
            {
                dist[dest] = dist[k] + cost;
                if(viz[dest] == 0)
                {
                    viz[dest] = 1;
                    q.push(dest);
                    cnt[dest]++;

                    if(cnt[dest] > n)
                    {
                        cout << "Ciclu negativ!";
                        exit(0);
                    }
                }
            }
        }
    }

}

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

int main()
{

    citire();
    Bellman_Ford();
    afisare();
}