Cod sursa(job #2864282)

Utilizator VipioanaMirea Oana Teodora Vipioana Data 7 martie 2022 18:53:34
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#define inf 1000000001
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
const int N=5e4+1;
int n,m,nrd[N],d[N];
vector <pair<int,int>> a[N];
queue <int> q;
bool inqueue[N];

bool bellmanford(){
    for(int i=1; i<=n; i++)
        d[i]=inf;
    d[1]=0;
    q.push(1);
    nrd[1]=inqueue[1]=1;
    while(!q.empty()){
        int x=q.front();
        q.pop();
        inqueue[x]=0;
        for(auto j:a[x]){
            int y=j.first;
            int c=j.second;
            if(d[x]+c<d[y]){
                d[y]=d[x]+c;
                if(!inqueue[y]){
                    q.push(y);
                    nrd[y]++;
                    inqueue[y]=1;
                    if(nrd[y]==n)
                        return 0;
                }
            }
        }
    }
    return 1;
}

int main()
{
    f>>n>>m;
    for(int i=1; i<=m; i++){
        int x,y,c;
        f>>x>>y>>c;
        a[x].push_back({y,c});
    }
    if(!bellmanford())
        g<<"Ciclu negativ!";
    else
        for(int i=2; i<=n; i++)
            g<<d[i]<<" ";
    return 0;
}