Cod sursa(job #2557329)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 25 februarie 2020 18:54:11
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
#define pb push_back

using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int MAXN = 50005, INF = 0x3f3f3f3f;

int dist[MAXN], vis[MAXN], n, m;
vector<pair<int, int>> graph[MAXN];
queue<int> q;

void read()
{
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int x, y, c;
        fin >> x >> y >> c;
        graph[x].pb({y, c});
    }
}

void init()
{
    for (int i = 1; i <= n; ++i)
        dist[i] = INF;
}

bool bf()
{
    dist[1] = 0;
    q.push(1);
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        ++vis[node];
        if (vis[node] == n)
            return false;
        for (const auto& it: graph[node])
            if (dist[it.first] > dist[node] + it.second) {
                dist[it.first] = dist[node] + it.second;
                q.push(it.first);
            }
    }
    return true;
}

void print()
{
    for (int i = 2; i <= n; ++i)
        fout << dist[i] << ' ';
}

int main()
{
    read();
    init();
    if (bf() == true)
        print();
    else
        fout << "Ciclu negativ!";
    return 0;
}