Cod sursa(job #2646032)

Utilizator OvidRata Ovidiu Ovid Data 30 august 2020 15:51:36
Problema Algoritmul Bellman-Ford Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include<bits/stdc++.h>
using namespace std;
#define INIT  ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define mp make_pair
#define pb push_back
#define ft first
#define sc second
#define ll long long
#define pii pair<int, int>
#define count_bits __builtin_popcount
#define int ll

int t, n, m, k, a[300010], q, l, r;

ifstream fin("bellmanford.in"); ofstream fout("bellmanford.out");
#define cin fin
#define cout fout
pair<pii, int> e[250010];
int d[50010];
vector<pii> g[50010];

int32_t main(){
INIT
cin>>n>>m;
int inf=((int)10e17);
for(int i=2; i<=n; i++){d[i]=inf;}
d[1]=0;

for(int i=1; i<=m; i++){
    int x, y, c;cin>>x>>y>>c;
    e[i]=mp(mp(x, y), c);
    g[x].pb(mp(y, c));
}
queue<int> q; q.push(1);
int ft1=1, lt1=1;
for(int i=1; i<=n; i++){
    int ft2=0, lt2=0;
    while(!q.empty()){
        int x=q.front(); q.pop();
        for(pii pr:g[x]){
            int y=pr.ft, c=pr.sc;
            if(d[y]>(d[x]+c) ){
            d[y]=min(d[x]+c, d[y]);
            q.push(y);
            if(ft2==0){ft2=y;}
            lt2=y;
            }
        }
        if(x==lt1){break;}
    }
    lt1=lt2; ft1=ft2;
}

for(int j=1; j<=m ;j++){
    if(d[e[j].ft.sc]>(d[e[j].ft.ft]+e[j].sc) ){
        cout<<"Ciclu negativ!"; return 0;
    }
}
for(int i=2; i<=n; i++){
    cout<<d[i]<<" ";
}


return 0;
}