Cod sursa(job #3251599)

Utilizator IleaIlea Bogdan Ilea Data 26 octombrie 2024 11:29:41
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>

using namespace std;

string file="bellmanford";
ifstream fin(file+".in");
ofstream fout(file+".out");

map<int, map<int, int> > g;
vector<bool> viz;
vector<int> b, nr;
int n, m;
void bellmanFord(int i)
{
    queue<int> q;
    q.push(i);
    while (!q.empty()){
        i=q.front();
        q.pop();
        for (auto it:g[i]){
            if (!viz[it.first] || b[it.first]>b[i]+it.second){
                b[it.first]=b[i]+it.second;
                q.push(it.first);
                viz[it.first]=1;
                nr[it.first]++;
                if (nr[it.first]>=n){
                    fout<<"Ciclu negativ!";
                    exit(0);
                }
            }
        }
    }
}
int main()
{
    fin>>n>>m;
    for (int i=0; i<m; i++){
        int x, y, z;
        fin>>x>>y>>z;
        g[x][y]=z;
    }
    nr.resize(n+1), b.resize(n+1), viz.resize(n+1);
    viz[1]=1;
    bellmanFord(1);
    for (int i=2; i<=n; i++){
        fout<<b[i]<<" ";
    }
    return 0;
}