Cod sursa(job #2696881)

Utilizator dariahazaparuHazaparu Daria dariahazaparu Data 17 ianuarie 2021 01:17:51
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

const int N_MAX = 100005;
const int INF = 1e9;

std :: vector <std :: pair <int, int> > graph[N_MAX];
std :: queue <int> q;
int dist[N_MAX], cicle[N_MAX];
bool vis[N_MAX];
int n, m;

int main()
{
    std :: ifstream fin("bellamnford.in");
    std :: ofstream fout("bellmanford.out");
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {   int a, b, cost;
        fin >> a >> b >> cost;
        graph[a].emplace_back(b, cost);
    }
    for (int i = 1; i <= n; ++i) {
        dist[i] = INF;
    }

    dist[1] = 0;
    vis[1] = true;
    q.push(1);
    while (q.empty() != 1)
    {
        int node = q.front();
        for (int i = 1; i <= graph[node].size(); ++i)
        {
            int next = graph[node][i].first;
            int cost = graph[node][i].second;
            if (dist[node] + cost < dist[next])
            {
                dist[next] = dist[node] + cost;
                if (!vis[next])
                {
                    vis[next] = true;
                    q.push(next);
                    cicle[next]++;
                    if (cicle[next] >= n)
                    {
                        fout << "Ciclu negativ!";
                        return 0;
                    }
                }
            }
        }
        vis[node] = false;
        q.pop();
    }
    for (int i = 2; i <= n; ++i) fout << dist[i] << " ";

    return 0;
}