Cod sursa(job #3282717)

Utilizator mateilucaLuca Matei Gabriel mateiluca Data 6 martie 2025 15:27:32
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
#define oo 2000000000

using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, d[50005], cnt[50005];
bool viz[50005];
vector< pair<int, int> > G[50005];
queue<int> q;
void Bellman_Ford(int x)
{
    int nod, cost;
    for(int i = 1;i <= n;i++)
        d[i] = oo;
    q.push(x);
    d[x] = 0;
    viz[x] = 1;
    cnt[x] = 1;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        viz[x] = 0;
        for(auto e : G[x])
        {
            nod = e.first;
            cost = e.second;
            if(d[nod] > d[x] + cost)
            {
                d[nod] = d[x] + cost;
                if(viz[nod] == 0)
                {
                    viz[nod] = 1;
                    q.push(nod);
                    cnt[nod]++;
                    if(cnt[nod] > n)
                    {
                        cout << "Ciclu Negativ!";
                        exit(0);
                    }
                }
            }
        }
    }
}

int main()
{
    int i, j, c;
    fin >> n >> m;
    while(m)
    {
        fin >> i >> j >> c;
        G[i].push_back({j, c});
        m--;
    }
    Bellman_Ford(1);
    for(i = 2;i <= n;i++)
        fout << d[i] << " ";
    fout << "\n";
    fout.close();
    return 0;
}