Cod sursa(job #2693554)

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

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

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

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

void bellmanford(int start)
{
    queue<int> qu;
    vector<int> distance(n + 1, INT_MAX);
    qu.push(start);
    distance[start] = 0;

    while(!qu.empty())
    {
        int curr = qu.front();
        qu.pop();
        for(auto e : Graph[curr])
        {
            if(distance[e.direct] > distance[curr] + e.weight)
            {
                distance[e.direct] = distance[curr] + e.weight;
                qu.push(e.direct);
                visited[e.direct]++;
                if(visited[e.direct] >= 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;
}