Cod sursa(job #2843925)

Utilizator oporanu.alexAlex Oporanu oporanu.alex Data 3 februarie 2022 12:07:04
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
 
const unsigned nmax = 50005;
 
struct edge{
    int i;
    int j;
    int cost;
    edge(int _i, int _j, int _cost): i(_i), j(_j), cost(_cost) {}
};
int main()
{
    int N, M;
    vector<pair<int, int>> adj[nmax];
    queue<int> q;
    bool inQ[nmax] = {false};
    int distMin[nmax];
    int cnt[nmax] = {0};
    fin >> N >> M;
    for(int i = 1; i <= M; ++i){
        int src, dst, cost;
        fin >> src >> dst >> cost;
        adj[src].push_back(make_pair(dst, cost));
    }
    distMin[1] = 0;
    for(int i = 2; i <= N; ++i)
        distMin[i] = INT_MAX / 2;
    q.push(1);
    inQ[1] = true;
    while(!(q.empty())){
        int i = q.front();
        q.pop();
        inQ[i] = false;
        for(auto vecin: adj[i]){
            int j = vecin.first;
            int cost = vecin.second;
            if(distMin[i] + cost < distMin[j]){
                distMin[j] = distMin[i] + cost;
                if(inQ[j] == false)
                    {   q.push(j);
                        inQ[j] = true;
                        ++cnt[j];
                        if(cnt[j] >= N - 1)
                            {
                                fout << "Ciclu negativ!\n";
                                return 0;
                            }
                    }
 
            }
        }
    }
    for(int i = 2; i <= N; ++i)
        fout << distMin[i] << ' ';
    return 0;
}