Cod sursa(job #2557350)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 25 februarie 2020 19:01:51
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 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;

bool inQ[MAXN];
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;
    ++vis[1];
    q.push(1);
    inQ[1] = true;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        inQ[node] = false;
        for (const auto& it: graph[node])
            if (dist[it.first] > dist[node] + it.second) {
                dist[it.first] = dist[node] + it.second;
                if (inQ[it.first] == false) {
                    ++vis[it.first];
                    if (vis[it.first] == n)
                        return false;
                    inQ[it.first] = true;
                    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;
}