Cod sursa(job #3271841)

Utilizator Theo14Ancuta Theodor Theo14 Data 27 ianuarie 2025 15:31:16
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb
#include<bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

//Dijkstra
/*
const int NMAX = 5e4;
const int INF = 1e9;
vector< pair<int, int> > G[NMAX + 1];
int d[NMAX + 1];
int vis[NMAX + 1];
int n,m;

void Dijkstra(int nod)
{
      for(int i = 1; i <= n; i++) {
        d[i] = INF;
    }
    d[nod] = 0;
    priority_queue< pair<int, int>, vector< pair<int, int> >, greater < pair<int, int> > > s;
    s.push({d[nod], nod});
    while(!s.empty()) {
        int node = s.top().second;
        s.pop();
        if(vis[node]) {
            continue;
        }
        vis[node] = 1;
        for(auto next : G[node]) {
            int vecin = next.first;
            int cost_muchie = next.second;
            if(!vis[vecin] && d[vecin] > d[node] + cost_muchie) {
                d[vecin] = d[node] + cost_muchie;
                s.push({d[vecin], vecin});
            }
        }
    }
    for(int i = 2; i <= n; i++) {
        if(d[i] == INF) {
            d[i] = 0;
        }
        cout << d[i] << ' ';
    }
}
*/

const int NMAX = 50000;
const int INF = 1e9;
int n,m,d[NMAX+3],in[NMAX+3],nr[NMAX+3];
vector< pair<int,int> >v[NMAX+3];
queue<int>q;

void BellmanFord(int x)
{
    int i;
    for(i=1;i<=n;i++)
        d[i]=INF,in[i]=0,nr[i]=0;
    d[x]=0;
    in[x]=1;
    nr[x]=1;
    q.push(x);
    while(!q.empty())
    {
        int nod=q.front();
        q.pop();
        in[nod]=0;
        for(auto it:v[nod])
        {
            int p=it.first;
            int z=it.second;
            if(d[p]>d[nod]+z)
            {
                d[p]=d[nod]+z;
                if(in[p]==0)
                {
                    nr[p]++;
                    if(nr[p]==n)
                    {
                        g<<"Ciclu negativ!";
                        return;
                    }
                    q.push(p);
                    in[p]=1;
                }
            }
        }
    }
    for(i=2;i<=n;i++)
        g<<d[i]<<" ";
}

int main()
{
    int i,x,y,c;
    f>>n>>m;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>c;
        v[x].push_back(make_pair(y,c));
    }
    BellmanFord(1);
    return 0;
}