Cod sursa(job #3337155)

Utilizator DavidAA007Apostol David DavidAA007 Data 26 ianuarie 2026 22:58:35
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n,m,i,j,x,y,c1,ok;
int d[50005],viz[50005],c[50005];
// relaxam de n-1 ori toate muchiile
vector<pair<int,int>>G[50005];
queue<pair<int,int>>q;
void bellman_ford(int k)
{
    d[k]=0;
    q.push({k,0});
    viz[k]=1;
    while(!q.empty())
    {
        int j=q.front().first;
        int cost=q.front().second;
        q.pop();
        viz[j]=0;
        for(auto x:G[j])
        {
            if(d[x.first]>d[j]+x.second)
            {
                d[x.first]=d[j]+x.second;
                if(viz[x.first] == 0) // nu este in coada
                {
                    q.push({x.first,d[x.first]});
                    viz[x.first]=1;
                    c[x.first]++;
                    if(c[x.first]>n)
                    {
                        ok=0;
                        break;
                    }
                }
            }
        }
        if(ok==0)
            break;
    }
}
int main()
{
    fin>>n>>m;
    for(i=1;i<=m;i++)
    {
        fin>>x>>y>>c1;
        G[x].push_back({y,c1});
    }
    for(i=1;i<=n;i++)
    {
        d[i]=inf;
    }
    ok=1;
    bellman_ford(1);
    if(ok==0)
    {
        fout<<"Ciclu negativ!";
        return 0;
    }
    for(i=2;i<=n;i++)
    {
        if(d[i]==inf)
            d[i]=0;
        fout<<d[i]<<" ";
    }
    return 0;
}