Cod sursa(job #3282893)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 7 martie 2025 12:53:04
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include<bits/stdc++.h>

using namespace std;

ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");

const int inf=1e7;
const int nmax=1e5+5;
vector <pair<int,int>> g[nmax];
queue <pair<int,int>> q;
int n, m, d[nmax], fr[nmax];

void bellman (int node)
{
    for (int i=1; i<=n; i++)
        d[i]=inf;
    d[node]=0;
    q.push({node,0});
    while (!q.empty())
    {
        int k=q.front().first;
        q.pop();
        if (fr[k]==n)
        {
            fout << "Ciclu negativ!";
            return;
        }
        for (auto i:g[k])
        {
            if (d[i.first]>d[k]+i.second)
            {
                fr[i.first]++;
                d[i.first]=d[k]+i.second;
                q.push(i);
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i=1; i<=m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        g[x].push_back({y,c});
    }
    bellman(1);
    for (int i=2; i<=n; i++)
    {
        if (d[i]==inf)
            fout << 0 << " ";
        else
            fout << d[i] << " ";
    }
}