Cod sursa(job #2684626)

Utilizator ddeliaioanaaDumitrescu Delia Ioana ddeliaioanaa Data 14 decembrie 2020 12:45:07
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
std::ifstream fin("bellmanford.in");
std::ofstream fout("bellmanford.out");

const int INF = 1e9;
std::vector<std::pair<int, int>> nei[50001];
int n, m, dist[50001], nr_of_viz[50001];
bool viz[50001];
std::queue<int> q;

bool bellmanford(){
    q.push(1);
    nr_of_viz[1]++;
    while(!q.empty()){
        int node = q.front(); q.pop();
        viz[node] = false;
        for(int i = 0; i < nei[node].size(); i++){
            int next_node = nei[node][i].first;
            int cost = nei[node][i].second;
            if(dist[node] + cost < dist[next_node]){
                dist[next_node] = dist[node] + cost;
                if(!viz[next_node]){ //daca nu e deja in coada
                    q.push(next_node);
                    viz[next_node] = true;
                    nr_of_viz[next_node]++;
                    if(nr_of_viz[next_node] >= n)
                        return false;
                }
            }
        }
    }
    return true;
}


int main()
{
    int i, x, y, cost;
    fin >> n >> m;
    for(i = 0; i < m; i++){
        fin >> x >> y >> cost;
        nei[x].push_back(std::make_pair(y, cost));
    }
    dist[1] = 0;
    for(i = 2; i <= n; i++)
        dist[i] = INF;

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



    return 0;
}