Cod sursa(job #3215101)

Utilizator ana_valeriaAna Valeria Duguleanu ana_valeria Data 14 martie 2024 18:01:16
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <queue>
#define MAX 50000
#define INF 1000000000
using namespace std;
ifstream cin ("bellmanford.in");
ofstream cout ("bellmanford.out");
int dist[MAX + 10], inQueue[MAX + 10], used[MAX + 10];
vector <pair <int, int>> graph[MAX + 10];
queue <int> q;
int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        graph[x].push_back({c, y});
    }
    for (int i = 2; i <= n; i++)
        dist[i] = INF;
    q.push(1);
    inQueue[1] = 1;
    used[1] = 1;
    int foundCycle = 0;
    while (!q.empty() && foundCycle == 0)
    {
        int node = q.front();
        q.pop();
        inQueue[node] = 0;
        for (const auto &it : graph[node])
        {
            int cost = it.first;
            int next = it.second;
            if (dist[next] > dist[node] + cost)
            {
                dist[next] = dist[node] + cost;
                if (inQueue[next] == 0)
                {
                    q.push(next);
                    inQueue[next] = 1;
                    used[next]++;
                    if (used[next] > n)
                        foundCycle = 1;
                }
            }
        }
    }
    if (foundCycle == 1)
        cout << "Ciclu negativ!";
    else
        for (int i = 2; i <= n; i++)
            cout << dist[i] << ' ';
    return 0;
}