Cod sursa(job #2693560)

Utilizator anacomoAna-Maria Comorasu anacomo Data 6 ianuarie 2021 13:35:44
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
#define MAX 50550
using namespace std;

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

int n, m;
struct Edge
{
    int destination, weight;
};

vector<Edge> Graph[MAX];
int visited[MAX];

void bellmanford(int startNode)
{
    queue<int> q;
    vector<int> distance(n + 1, INT_MAX);

    q.push(startNode);
    distance[startNode] = 0;

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

        for (auto edge : Graph[current])
        {
            if (distance[edge.destination] > distance[current] + edge.weight)
            {
                distance[edge.destination] = distance[current] + edge.weight;
                q.push(edge.destination);
                visited[edge.destination]++;
                if (visited[edge.destination] >= n)
                {
                    fout << "Ciclu negativ!";
                    return;
                }
            }
        }
    }
    for (int i = 2; i <= n; i++)
    {
        fout << distance[i] << " ";
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int source, destination, weight;
        fin >> source >> destination >> weight;
        Graph[source].push_back({destination, weight});
    }

    bellmanford(1);
    return 0;
}