Cod sursa(job #2693558)

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

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

int n, m;
struct Edge
{
    int dest;
    int weight;
    Edge(int d, int w) : dest(d), weight(w) {}
};

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

void bellmanford(int start)
{
    queue<int> q;
    vector<int> distance(n + 1, INT_MAX);
    q.push(start);
    distance[start] = 0;
    while (!q.empty())
    {
        int current = q.front();
        q.pop();
        for (auto edge : Graph[current])
        {
            if (distance[edge.dest] > distance[current] + edge.weight)
            {
                distance[edge.dest] = distance[current] + edge.weight;
                q.push(edge.dest);
                visited[edge.dest]++;
                if (visited[edge.dest] >= 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, direction, weight;
        fin >> source >> direction >> weight;
        Graph[source].push_back(Edge(direction, weight));
    }
    bellmanford(1);
    return 0;
}