Cod sursa(job #3158967)

Utilizator NathanBBerintan Emanuel Natanael NathanB Data 20 octombrie 2023 11:59:00
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#define cin fin
#define cout fout
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define eb emplace_back
#define Inf 0x3f3f3f3f
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef pair<ll,ll> pl;
typedef vector<pair<ll,ll>> vpl;
const int Nmax = 50001;
vpl G[Nmax];

int n,m;
queue<ll> q;
bool inq[Nmax],negcyc=false;
int cntinq[Nmax],dist[Nmax];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        cin>>x>>y>>c;
        G[x].eb(y,c);
    }
    memset(dist,Inf,sizeof dist);
    dist[1] = 0;
    q.push(1);
    inq[1] = true;
    while(!q.empty()&&!negcyc)
    {
        int nod = q.front();
        //cout<<"nod = "<<nod<<'\n';
        q.pop();
        inq[nod] = false;
        for(auto c:G[nod])
        if(dist[nod] < Inf)
        {
            if(dist[nod] + c.second < dist[c.first])
            {
                dist[c.first] = dist[nod] + c.second;
                if(!inq[c.first])
                {
                    if(cntinq[c.first] > n) negcyc = true;
                else
                {
                    q.push(c.first);
                    inq[c.first] = true;
                    cntinq[c.first]++;
                }
                }
            }
        }
    }
    if(!negcyc)
    {
        for(int i=2;i<=n;i++)
            cout<<dist[i]<<" ";
    }
    else cout<<"Ciclu negativ!\n";
    return 0;
}