Cod sursa(job #3249093)

Utilizator Stefan_DomuncoStefan Domunco Stefan_Domunco Data 14 octombrie 2024 18:55:18
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 5e4 + 4, DMAX = 1e9;
int n, m;
vector < pair <int, int> > g[NMAX];
long long dist[NMAX];
int passed[NMAX];

void setup(){
    for(int i = 0; i < NMAX; ++i)
        dist[i] = DMAX, passed[i] = 0;
}

bool bellmanford(int startingNode){
    setup();
    dist[startingNode] = 0;
    bitset <NMAX> inQueue;
    queue <int> q;

    q.push(startingNode);

    int head;

    while(!q.empty()){
        head = q.front();
        q.pop();
        inQueue[head] = 0;

        if(passed[head] > n)
            return false;

        passed[head]++;

        for(auto &it: g[head])
            if(dist[it.first] > dist[head] + it.second){
                dist[it.first] = dist[head] + it.second;
                if(inQueue[it.first] == 0){
                    inQueue[it.first] = 1;
                    q.push(it.first);
                }
            }
    }

    return true;
}


int main()
{
    fin >> n >> m;

    for(int i = 1; i <= n; ++i){
        int a, b, c;
        fin >> a >> b >> c;
        g[a].push_back({b, c});
    }

    if(bellmanford(1))
        for(int i = 2; i <= n; ++i)
            fout << dist[i] << ' ';
    else fout << "Ciclu negativ!";


    return 0;
}