Cod sursa(job #2806555)

Utilizator As932Stanciu Andreea As932 Data 22 noiembrie 2021 19:16:50
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
#define per pair<int,int>
#define inf 2e9

using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

const int nmax = 5e4 + 5;

int n, m, cost[nmax], fq[nmax];
queue <int> q;
vector <per> v[nmax];

void read(){
    fin >> n >> m;

    for(int i = 1; i <= m; i++){
        int x, y, c;
        fin >> x >> y >> c;
        v[x].push_back(make_pair(y, c));
    }
}

void solve(){
    q.push(1);
    for(int i = 2; i <= n; i++)
        cost[i] = inf;

    while(!q.empty()){
        int x = q.front();
        q.pop();

        for(int i = 0; i < v[x].size(); i++){
            int y = v[x][i].first;
            if(cost[y] > cost[x] + v[x][i].second){
                cost[y] = cost[x] + v[x][i].second;
                q.push(y);
                fq[y]++;

                if(fq[y] >= n){
                    fout << "Ciclu negativ!";
                    return;
                }
            }
        }
    }

    for(int i = 2; i <= n; i++)
        fout << cost[i] << " ";
}

int main()
{
    read();
    solve();

    return 0;
}